Scala 修饰符和类型参数化 [英] Scala Modifiers and Type parametrization
问题描述
我正在创建一个备忘录类.
I'm creating a memoization class.
每个类都记住一个函数类型并具有以下定义:
Each class memoizes a function type and has the following definition:
class MemoizedFunction1[-T1, +R](f: T1 => R) {
private[this] val cache = mutable.Map[T1, R]()
def apply(t: T1): R = cache.getOrElseUpdate(t,f(t))
}
这可以很好地编译并按预期工作.但是,如果我删除修改后的 private[this]
,我会收到以下错误:
This compiles nicely and works as expected.
However, if I remove the modified private[this]
I get the following error:
contravariant type T1 occurs in invariant position in type => scala.collection.mutable.Map[T1,R] of value cache
为什么当我删除修饰符时,逆变类型 T1 突然干扰了 Map 的不变类型?修饰符如何影响类型参数化?
Why is that, when I remove the modifier, suddenly the contravariant type T1 interferes with the invariant type of the Map? How do modifiers affect type parametrization?
推荐答案
并不是我完全理解,但是在 Scala 语言规范 2.9 第 45 页
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
不会检查类的对象私有或对象保护值、变量或方法(第 5.2 节)中对类型参数的引用的差异位置.在这些成员的类型参数可以出现在任何地方,而不会限制其合法的变化注释.
为了简化您的示例,根据规范,这很好:
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")
}
但是如果你删除 [this]
它会抱怨.在某种程度上,这是有道理的,因为如果它不是对象私有的或受保护的,逆变返回类型可能会泄漏到对象之外并导致运行时错误.
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.
这篇关于Scala 修饰符和类型参数化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!