Search code examples
scalaimplicitambiguous

Why in-scope implicit values typed A and B are not ambiguous when B extends A?


Why does the code in Test2 compile even though we clearly have ambiguous implicit values?


object Method {
  def foo(implicit i: A): Unit = println(i.i)
}

trait A {
  val i: Int
}
class B(override val i: Int) extends A

object Test1 {
  implicit val i1: A = new A {
    val i: Int = 20
  }
}

object Test2 {
  implicit val i2: B = new B(10)
  import Test1._
  // This compiles fine and prints 10
  Method.foo
}

object Test3 {
  implicit val i2: A = new B(10)
  import Test1._
  // This does not compile, get `ambiguous implicit values`
  Method.foo
}

Solution

  • In Test2 there is no ambiguity. i2 has more specific type than i1, so i2 has higher priority than i1.

    In Test3 i1 and i2 have the same type A, so this is ambiguity.

    https://stackoverflow.com/a/57934397/5249621