The Scala example below shows a situation where a required implicit parameter (of type TC[C]
) can be provided by both implicit methods in scope, a
and b
. But when run, no ambiguity results, and it prints "B".
object Example extends App{
trait A
trait B extends A
class C extends B
class TC[X](val label: String)
implicit def a[T <: A]: TC[T] = new TC[T]("A")
implicit def b[T <: B]: TC[T] = new TC[T]("B")
println(implicitly[TC[C]].label)
}
Note that the only different between implicit methods a
and b
are the type bounds, and both of them can match TC[C]
. If the method b
is removed, then a
is implicitly resolved instead.
While I find this behaviour convenient in practice, I'd like to understand whether it is a specified language feature, or just an implementation quirk.
Is there a language rule or principle by which the compiler prioritizes b
over a
, rather than viewing them as equivalent and thus ambiguous options?