scala 2.8中隐式转换的问题
我想编写 Tuple2[A,B] 到 Seq[C] 的隐式转换,其中 C 是 A 和 B 的超类型。 我的第一次尝试如下:
implicit def t2seq[A,B,C](t: (A,B))(implicit env: (A,B) <:< (C,C)): Seq[C] = {
val (a,b) = env(t)
Seq(a,b)
}
但它不起作用:
scala> (1,2): Seq[Int]
<console>:7: error: type mismatch;
found : (Int, Int)
required: Seq[Int]
(1,2): Seq[Int]
^
虽然这个有效:
class Tuple2W[A,B](t: (A,B)) {
def toSeq[C](implicit env: (A,B) <:< (C,C)): Seq[C] = {
val (a,b) = env(t)
Seq(a,b)
}
}
implicit def t2tw[A,B](t: (A,B)): Tuple2W[A,B] = new Tuple2W(t)
用例:
scala> (1,2).toSeq
res0: Seq[Int] = List(1, 2)
我不知道为什么第一个解决方案没有按预期工作。 Scala 版本 2.8.0.r22634-b20100728020027(Java HotSpot(TM) 客户端虚拟机、Java 1.6.0_20)。
I want to write a implicit conversion of Tuple2[A,B] to Seq[C] where C is super type of both A and B.
My first try as following:
implicit def t2seq[A,B,C](t: (A,B))(implicit env: (A,B) <:< (C,C)): Seq[C] = {
val (a,b) = env(t)
Seq(a,b)
}
But it doesn't work:
scala> (1,2): Seq[Int]
<console>:7: error: type mismatch;
found : (Int, Int)
required: Seq[Int]
(1,2): Seq[Int]
^
While this one works:
class Tuple2W[A,B](t: (A,B)) {
def toSeq[C](implicit env: (A,B) <:< (C,C)): Seq[C] = {
val (a,b) = env(t)
Seq(a,b)
}
}
implicit def t2tw[A,B](t: (A,B)): Tuple2W[A,B] = new Tuple2W(t)
Use case:
scala> (1,2).toSeq
res0: Seq[Int] = List(1, 2)
I have no idea why the first solution didn't work as expected.
Scala version 2.8.0.r22634-b20100728020027 (Java HotSpot(TM) Client VM, Java 1.6.0_20).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要限制的参数已经绑定在周围范围内(就像您第二次尝试时那样),则只需使用
<:<
,因此在您的情况下就足够了。
我猜你的第一次尝试没有成功,因为它对于类型推断器来说太复杂了。
You only need to use
<:<
if the parameters to be restricted are already bound in the surrounding scope (as they are in your second try), so in your caseis sufficient.
I would guess that your first try did not work as it is too complex for the type inferencer.