Scala:implicits,子类和成员类型

时间:2014-10-01 23:32:54

标签: scala

让我们说我们想要使用类型类来实现漂亮的打印:

trait Printer[T] {def print(t: T)}

使用ints的默认实现:

implicit object IntPrinter extends Printer[Int] {
    override def print(i : Int): Unit = println(i)
}

我们要打印的具体类型是:

trait Foo {
    type K
    val k: K
}

class IntFoo extends Foo {
    override type K = Int
    override val k = 123
}

冷却。现在我想为所有具有可打印Ks的Foos构建打印机

implicit def fooPrinter[FP <: Foo](implicit ev: Printer[FP#K]): Printer[FP] =
    new Printer[FP] {
        override def print(f: FP): Unit = {
            Predef.print("Foo: ")
            ev.print(f.k)
        }
    }

让我们检查一下implicits是否已解决:

def main(args: Array[String]) {
    implicitly[Printer[Int]]
    implicitly[Printer[IntFoo]]
}

scalac 2.11.2说:

diverging implicit expansion for type Sandbox.Printer[Int]
    starting with method fooPrinter in object Sandbox
        implicitly[Printer[Int]]

whaat?

好的,让我们重写fooPrinter:

implicit def fooPrinter[KP, FP <: Foo {type K = KP}](implicit ev: Printer[KP]) =
    new Printer[FP] {
        override def print(f: FP): Unit = {
            Predef.print("Foo: ")
            ev.print(f.k)
        }
    }

这适用于2.11,但第一种方法有什么问题? 不幸的是我们在2.10,而第二个解决方案仍然不起作用。它会编译,直到我们再添加一个sime打印机,如

implicit object StringPrinter extends Printer[String] {
    override def print(s : String): Unit = println(s)
}

它神秘地打破了打印机[IntFoo]的隐含:

could not find implicit value for parameter e:   
    Sandbox.Printer[Sandbox.IntFoo]

编译器错误?

1 个答案:

答案 0 :(得分:2)

隐含声明的顺序很重要。在您的源代码中重新排序原始代码

implicit object IntPrinter ...
...
implicit def fooPrinter ...

implicit def fooPrinter ...
...
implicit object IntPrinter ...