I stumbled upon this problem when trying to precisely answer this SO question. I tried to follow the specification step by step and realized something’s wrong.
Let’s try it again. We have a typeclass and two polymorphic implicit def
s for it:
trait Base
class Klass extends Base
trait TC[T]
object TC {
implicit def unbounded[T]: TC[T] = new TC[T] {}
implicit def bounded[T <: Base]: TC[T] = new TC[T] {}
}
Now, if we demand implicitly[TC[Klass]]
, the compiler will chose bounded
, but I can’t see how this can be deduced from the specification. Let’s try:
First, we need to follow specificity rules in order to find out if bounded
is as specific as unbounded
and vice versa.
The specification says:
A polymorphic method of type [a1 >: L1 <: U1,…,an >: Ln <: Un]T
is as specific as some other member of type S
if T
is as specific as S
under the assumption that for i=1,…,n
each ai
is an abstract type name bounded from below by Li
and from above by Ui
.
Applying this to bounded
and unbounded
we get two polymorphic method types [T <: Base]A[T]
and [T]A[T]
. The rule above apparently wants me to somehow “strip” the type parameter from [T <: Base]A[T]
and leaving something like type T <: Base; A[T]
(which is not the same as A[T] forSome { type T <: Base }
?). Then, I have to decide whether type T <: Base; A[T]
is as specific as [T]A[T]
. The first type is no longer polymorphic while the second one still is, so the next rule to apply is:
A member of any other type is always as specific as a parameterized method or a polymorphic method.
This way we deduce that bounded
is as specific as unbounded
.
However, using exactly the same logic we could deduce that unbounded
is as specific as bounded
and type bounds have absolutely no influence on that.
This would in turn mean that neither bounded
is more specific than unbounded
nor the other way around which would mean that bounded
should not be chosen over unbounded
and we should get an ambiguous implicits error.
So this already falls apart here, before we even get to the rule that I initially asked about.
Either I’m missing something or it seems that this specification is off.