I want to understand why scala compiler emits error for the following snippet:
import scala.collection.mutable
class X[+A, +C] {
val x = mutable.Map.empty[Int, mutable.Builder[A, C]]
}
The error ouput:
<console>:13: error: covariant type A occurs in invariant position in type => scala.collection.mutable.Map[Int,scala.collection.mutable.Builder[A,C]] of value x
val x = mutable.Map.empty[Int, mutable.Builder[A, C]]
^
As I understand it, the variance rule is deduced outside-in like this:
x
is at positive position.- type parameters of
mutable.Map.empty
is at neutral position. - Because of
2.
and variance annotation ofBuilder[-Elem, +To]
,A
is at negative position, andC
is at positive position.
Therefore, A
being covariant was misplaced in a negative (contravariant) position -Elem
. Why does compiler say that it's an "invariant position"?
If I make A
invariant, as in:
class X[A, +C] {
val x = mutable.Map.empty[Int, mutable.Builder[A, C]]
}
The error became:
On line 2: error: covariant type C occurs in invariant position in type scala.collection.mutable.Map[Int,scala.collection.mutable.Builder[A,C]] of value x
I thought C
position should have been positive (covariant), but compiler says it's also invariant?