trait Eq[-A] {
def eq(a: A, b: A): Boolean
}
object Eq {
implicit object IntEq extends Eq[Int] {
def eq(a: Int, b: Int) = a == b
}
}
trait Supertrait[+A]
object Supertrait {
implicit def Eq[A: Eq]: Eq[Supertrait[A]] = ???
}
trait Subtrait[+A] extends Supertrait[A]
object Subtrait {
implicit def Eq[A: Eq]: Eq[Subtrait[A]] = ???
}
def f[A](x: Subtrait[A])(implicit ev: Eq[Subtrait[A]]) = ???
f(new Subtrait[Int] {})
When compiling this code, the following error occurs:
Error:(32, 4) ambiguous implicit values:
both method Eq in object Supertrait of type [A](implicit evidence$1: Eq[A])Eq[Supertrait[A]]
and method Eq in object Subtrait of type [A](implicit evidence$2: Eq[A])Eq[Subtrait[A]]
match expected type Eq[Subtrait[Int]]
f(new Subtrait[Int] {})
^
Why doesn't the implicit def
in the Subtrait
companion object has higher precedence than the one in Supertrait
?
I'd like that implicit def
s in the companion object of subtraits have higher precedence than those in supertraits.
UPDATE
The LowPriorityImplicits
trick does not work either. See Enforcing precedence in implicit instances in Scala.
It looks like your code violates the Non-Ambiguity Rule for implicits.
From Programming in Scala, 1st edition:
The complete text can be found here.