I\'m creating a memoization class.
Each class memoizes a function type and has the following definition:
class MemoizedFunction1[-T1, +R](f: T1 => R)
Not that I understand all of it, but this is addressed in section 4.5 (Variance Annotations) of the Scala Language Specification 2.9 on page 45
References to the type parameters in object-private or object-protected values, variables, or methods (§5.2) of the class are not checked for their variance position. In these members the type parameter may appear anywhere without restricting its legal variance annotations.
To simplify your example, according to the spec, this is fine:
class Inv[T]
class Foo[-T] {
private[this] val a: Inv[T] = sys.error("compiles")
protected[this] val b: Inv[T] = sys.error("compiles")
}
But if you remove [this]
it will complain. At some level it makes sense since if it is not object private or protected the contravariant return type could leak outside the object and cause a runtime error.