Search code examples
scalaimplicitoperator-precedenceimplicit-parameters

Scala type constraint precedence in implicit resolution


I have these 2 implicits

trait A[T] {
  val name: String
}

trait B

object A {
  implicit def product[T <: Product] = new A[T] {
    override val name: String = "product"
  }

  implicit def childOfB[T <: Product with B] = new A[T] {
    override val name: String = "child of B"
  }
}

and if I try to find an implicit instance of A[C] where C is

case class C() extends B

childOfB will be selected.

I know it is logical but why does this happen? I cannot find it documented anywhere.


Solution

  • Scala Language Specification says:

    If there are several eligible arguments which match the implicit parameter's type, a most specific one will be chosen using the rules of static overloading resolution.

    Overloading resolution has a notion of one symbol being more specific than other. Precise, general definition of specificity is quite complex (as you can see in the specification linked above) but in your case it boils down to the fact that childOfB covers strictly a subset of types covered by product and therefore is more specific.