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

不羁的心 提交于 2019-12-10 19:22:47

问题


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
}

回答1:


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



来源:https://stackoverflow.com/questions/58027241/why-in-scope-implicit-values-typed-a-and-b-are-not-ambiguous-when-b-extends-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!