pimp-my-library模式允许我通过提供从该类到实现该方法的隐式转换来向类添加方法。
然而,Scala不允许进行两次这样的隐式转换,因此我无法使用隐式A
到C
从A
转到B
而另一个隐式转换{ {1}}到B
。有没有解决这个限制的方法?
答案 0 :(得分:104)
Scala对自动转换的限制是添加方法,即在尝试查找方法时不会应用多个转换。例如:
class A(val n: Int)
class B(val m: Int, val n: Int)
class C(val m: Int, val n: Int, val o: Int) {
def total = m + n + o
}
// This demonstrates implicit conversion chaining restrictions
object T1 { // to make it easy to test on REPL
implicit def toA(n: Int): A = new A(n)
implicit def aToB(a: A): B = new B(a.n, a.n)
implicit def bToC(b: B): C = new C(b.m, b.n, b.m + b.n)
// won't work
println(5.total)
println(new A(5).total)
// works
println(new B(5, 5).total)
println(new C(5, 5, 10).total)
}
编辑:自Scala 2.11 https://issues.scala-lang.org/browse/SI-7629 以来,不推荐使用视图边界('<%')(您可以使用类型类)
但是,如果隐式定义本身需要隐式参数(View bound),则Scala 将根据需要查找其他隐式值。从最后一个例子继续:
// def m[A <% B](m: A) is the same thing as
// def m[A](m: A)(implicit ev: A => B)
object T2 {
implicit def toA(n: Int): A = new A(n)
implicit def aToB[A1 <% A](a: A1): B = new B(a.n, a.n)
implicit def bToC[B1 <% B](b: B1): C = new C(b.m, b.n, b.m + b.n)
// works
println(5.total)
println(new A(5).total)
println(new B(5, 5).total)
println(new C(5, 5, 10).total)
}
你可能会说,“魔术!”不是这样。以下是编译器如何翻译每一个:
object T1Translated {
implicit def toA(n: Int): A = new A(n)
implicit def aToB(a: A): B = new B(a.n, a.n)
implicit def bToC(b: B): C = new C(b.m, b.n, b.m + b.n)
// Scala won't do this
println(bToC(aToB(toA(5))).total)
println(bToC(aToB(new A(5))).total)
// Just this
println(bToC(new B(5, 5)).total)
// No implicits required
println(new C(5, 5, 10).total)
}
object T2Translated {
implicit def toA(n: Int): A = new A(n)
implicit def aToB[A1 <% A](a: A1): B = new B(a.n, a.n)
implicit def bToC[B1 <% B](b: B1): C = new C(b.m, b.n, b.m + b.n)
// Scala does this
println(bToC(5)(x => aToB(x)(y => toA(y))).total)
println(bToC(new A(5))(x => aToB(x)(identity)).total)
println(bToC(new B(5, 5))(identity).total)
// no implicits required
println(new C(5, 5, 10).total)
}
因此,当bToC
被用作隐式转换时,aToB
和toA
将作为隐式参数传递,而不是被链接为隐式转化
修改强>
相关问题:
答案 1 :(得分:12)
请注意,您也可以使用隐式参数构建圆圈。然而,这些由编译器检测,如下所示:
class Wrap {
class A(implicit b : B)
class B(implicit c : C)
class C(implicit a : A)
implicit def c = new C
implicit def b = new B
implicit def a = new A
}
给用户的错误并不像他们那样清楚;它只是抱怨could not find implicit value for parameter
所有三个建筑工地。这可能会在不太明显的情况下掩盖根本问题。
答案 2 :(得分:1)
Here's一个也会累积路径的代码。
import scala.language.implicitConversions
// Vertices
case class A(l: List[Char])
case class B(l: List[Char])
case class C(l: List[Char])
case class D(l: List[Char])
case class E(l: List[Char])
// Edges
implicit def ad[A1 <% A](x: A1) = D(x.l :+ 'A')
implicit def bc[B1 <% B](x: B1) = C(x.l :+ 'B')
implicit def ce[C1 <% C](x: C1) = E(x.l :+ 'C')
implicit def ea[E1 <% E](x: E1) = A(x.l :+ 'E')
def pathFrom(end:D) = end
pathFrom(B(Nil)) // res0: D = D(List(B, C, E, A))