低优先级含义中的歧义

时间:2016-03-17 18:28:33

标签: scala scala-implicits

我有以下Scala代码片段:

  import java.io.PrintWriter

  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }

  trait LowPriorityWrites {
    implicit object any extends Write[Any] {
      override def apply(out: PrintWriter)(x: Any) = out.print(x)
    }
  }

  object Write extends LowPriorityWrites {
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }

基本上,我想要实现的是首先在Write对象中查找隐式。如果没有,请从.toString回退到Any的默认LowPriorityWrites

但是,这种方法不起作用:

ambiguous implicit values:
[error]  both method iterable in object Write of type [A](implicit write: Write[A])Write[Traversable[A]]
[error]  and object any in trait LowPriorityWrites of type Write.any.type
[error]  match expected type Write[Seq[Long]]

0 个答案:

没有答案