What is Scala's static overloading rule?

2019-07-31 14:45发布

问题:

In many explanations about Scala's implicit precedence, it states that if there is more than one thing with the same precedence, Scala's "static overloading rule" is applied.

That rule isn't explained, though. It seems that this expression is used exclusively in this context. What is Scala's static overloading rule?

回答1:

This is explained in §6.26.3 of the Scala Language Specification. As also noted in this answer, there is a blog post that lists this resolution in a simpler way:

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.

An alternative A is more specific than an alternative B if the relative weight of A over B is greater than the relative weight of B over A.

For views, if A is as specific view as B, A gets a relative weight of 1 over B.

If A is defined in a derived class in which B is defined, A gets another relative weight.