参数化类型的多态

来源:互联网 发布:淘宝购物返利最高的 编辑:程序博客网 时间:2024/06/05 15:12



如果我们结合隐式转换implicits使用容器,我们会得到“特设的”多态性:即对容器写泛型函数的能力。

scala> trait Container[M[_]] { def put[A](x: A): M[A]; def get[A](m: M[A]): A }scala> implicit val listContainer = new Container[List] { def put[A](x: A) = List(x); def get[A](m: List[A]) = m.head }scala> implicit val optionContainer = new Container[Some] { def put[A](x: A) = Some(x); def get[A](m: Some[A]) = m.get }scala> def tupleize[M[_]: Container, A, B](fst: M[A], snd: M[B]) = {     | val c = implicitly[Container[M]]                                  | c.put(c.get(fst), c.get(snd))     | }tupleize: [M[_],A,B](fst: M[A],snd: M[B])(implicit evidence$1: Container[M])M[(A, B)]scala> tupleize(Some(1), Some(2))res33: Some[(Int, Int)] = Some((1,2))scala> tupleize(List(1), List(2))res34: List[(Int, Int)] = List((1,2))
0 0
原创粉丝点击