作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面的 Scala 示例显示了一种情况,其中一个必需的隐式参数(类型 TC[C]
)可以由作用域中的两个隐式方法提供,a
和 b
.但是当运行时,没有歧义结果,它打印“B”。
object Example extends App{
trait A
trait B extends A
class C extends B
class TC[X](val label: String)
implicit def a[T <: A]: TC[T] = new TC[T]("A")
implicit def b[T <: B]: TC[T] = new TC[T]("B")
println(implicitly[TC[C]].label)
}
a
和
b
是类型边界,它们都可以匹配
TC[C]
.如果方法
b
被删除,然后
a
而是隐式解析。
b
在
a
,而不是将它们视为等效且因此模棱两可的选项?
最佳答案
有一个关于此优先级的规则,即两个匹配项中最具体的将获得更高的优先级。来自 Scala Reference ,在 6.26.3 '重载分辨率'下:
The relative weight of an alternative A over an alternative B is a number from 0 to 2, defined as the sum of
- 1 if A is as specific as B, 0 otherwise, and
- 1 if A is defined in a class or object which is derived from the class or object defining B, 0 otherwise.
A class or object C is derived from a class or object D if one of the following holds:
- C is a subclass of D, or
- C is a companion object of a class derived from D, or
- D is a companion object of a class from which C is derived.
关于scala - 类型边界意外更改 Scala 隐式参数解析的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15852251/
我是一名优秀的程序员,十分优秀!