Ambiguity in Low priority implicits
Asked Answered
M

0

6

I have the following snippet of Scala code:

  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()
      }
    }
  }

Basically, what I want to achieve is that first look for an implicit in Write object. If not, fall back to the default .toString for Any from LowPriorityWrites.

But, this approach does not work:

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]]
Monocarpic answered 17/3, 2016 at 18:28 Comment(5)
Can't write a full answer at the moment, but if you make the fallback instance generic the priorities will work out just fine.Biparietal
Yup replacing Any with A worked. Thanks!Monocarpic
@TravisBrown: When you have a moment, write up an answer and I will accept it. It would be nice to know WHY Any does not work. Thanks!Monocarpic
Agreed wholeheartedly!Simasimah
Reasons are similar to those in the question #57934365Glossy

© 2022 - 2024 — McMap. All rights reserved.