3

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
}
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
samthebest
  • 30,803
  • 25
  • 102
  • 142
  • 2
    In **Test2** there is not ambiguity, because given the rules of implicit resolution. The most specific one will be chosen. And `i2` is most specific than `i1`, because **B** extends **A**. On the other hand, in **Test3** there is clear ambiguity that can't not be solved. – Luis Miguel Mejía Suárez Sep 20 '19 at 11:42

1 Answers1

4

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

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66