gpt4 book ai didi

scala - 类型边界意外更改 Scala 隐式参数解析的优先级

转载 作者:行者123 更新时间:2023-12-01 02:26:35 26 4
gpt4 key购买 nike

下面的 Scala 示例显示了一种情况,其中一个必需的隐式参数(类型 TC[C])可以由作用域中的两个隐式方法提供,ab .但是当运行时,没有歧义结果,它打印“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)
}

注意隐式方法之间的唯一区别 ab是类型边界,它们都可以匹配 TC[C] .如果方法 b被删除,然后 a而是隐式解析。

虽然我发现这种行为在实践中很方便,但我想了解它是指定的语言功能,还是只是一个实现怪癖。

是否存在编译器优先考虑的语言规则或原则 ba ,而不是将它们视为等效且因此模棱两可的选项?

最佳答案

有一个关于此优先级的规则,即两个匹配项中最具体的将获得更高的优先级。来自 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com