scala 2.8中隐式转换的问题

发布于 2024-09-13 01:28:02 字数 869 浏览 3 评论 0原文

我想编写 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晒暮凉 2024-09-20 01:28:02

如果要限制的参数已经绑定在周围范围内(就像您第二次尝试时那样),则只需使用 <:< ,因此在您的情况下

implicit def t2seq[A <: C,B <: C,C](t: (A,B)) = Seq(t._1, t._2)

就足够了。

我猜你的第一次尝试没有成功,因为它对于类型推断器来说太复杂了。

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 case

implicit def t2seq[A <: C,B <: C,C](t: (A,B)) = Seq(t._1, t._2)

is sufficient.

I would guess that your first try did not work as it is too complex for the type inferencer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文