为什么当B扩展A时,类型为A和B的作用域内隐式值不是模棱两可的? [英] Why in-scope implicit values typed A and B are not ambiguous when B extends A?

查看:85
本文介绍了为什么当B扩展A时,类型为A和B的作用域内隐式值不是模棱两可的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使我们显然具有模棱两可的隐式值,为什么Test2中的代码仍会编译?

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
}

推荐答案

Test2中没有歧义. i2具有比i1更具体的类型,因此i2具有比i1更高的优先级.

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

Test3 i1i2中具有相同的类型A,因此这是模棱两可的.

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

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

这篇关于为什么当B扩展A时,类型为A和B的作用域内隐式值不是模棱两可的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆