The Scala example below shows a situation where the required implicit parameter (of type TC[C] ) can be provided by both implicit scope methods and a and b . But there is no ambiguity at startup, 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 difference between the implicit methods a and b is the type boundaries, and both of them can correspond to TC[C] . If method b removed, then a will be implicitly allowed.
While I find this behavior convenient in practice, I would like to understand whether this is a given function of the language or just the complexity of the implementation.
Is there a language rule or principle by which the compiler selects b over a instead of treating them as equivalent and, therefore, ambiguous?
source share