我想使用返回类型 R 的单个函数映射 Scala 元组(或三元组,...)的元素。结果应该是一个具有 R 类型元素的元组(或三元组,...)。
OK,如果元组的元素来自相同的类型,映射不是问题:
scala> implicit def t2mapper[A](t: (A,A)) = new { def map[R](f: A => R) = (f(t._1),f(t._2)) }
t2mapper: [A](t: (A, A))java.lang.Object{def map[R](f: (A) => R): (R, R)}
scala> (1,2) map (_ + 1)
res0: (Int, Int) = (2,3)
但是是否也可以使这个解决方案通用,即以相同的方式映射包含不同类型元素的元组?
例子:
class Super(i: Int)
object Sub1 extends Super(1)
object Sub2 extends Super(2)
(Sub1, Sub2) map (_.i)
应该返回
(1,2): (Int, Int)
但是我找不到解决方案,以便映射函数确定 Sub1 和 Sub2 的超类型。我尝试使用类型边界,但我的想法失败了:
scala> implicit def t2mapper[A,B](t: (A,B)) = new { def map[X >: A, X >: B, R](f: X => R) = (f(t._1),f(t._2)) }
<console>:8: error: X is already defined as type X
implicit def t2mapper[A,B](t: (A,B)) = new { def map[X >: A, X >: B, R](f: X => R) = (f(t._1),f(t._2)) }
^
<console>:8: error: type mismatch;
found : A
required: X
Note: implicit method t2mapper is not applicable here because it comes after the application point and it lacks an explicit result type
implicit def t2mapper[A,B](t: (A,B)) = new { def map[X >: A, X >: B, R](f: X => R) = (f(t._1),f(t._2)) }
这里X >: B
似乎覆盖了X >: A
. Scala 不支持关于多种类型的类型边界吗?如果是,为什么不呢?