如何解释下面关于private[this]和variance的句子?

How to explain the following sentences about private[this] and variance?

第19章,"Programming in scala 2nd edition",如何解释粗体句?

object private members can be accessed only from within the object in which they are defined. It turns out that accesses to variables from the same object in which they are defined do not cause problems with variance. The intuitive explanation is that, in order to construct a case where variance would lead to type errors, you need to have a reference to a containing object that has a statically weaker type than the type the object was defined with. For accesses to object private values, however,this is impossible.

我认为解释 Martin 试图表达的内容的最直观方式是查看 Java 中的数组。 Java 中的数组是协变的,但不根据协变规则进行类型检查。这意味着它们在运行时而不是编译时爆炸:

abstract class Animal {}
class Girafee extends Animal {}
class Lion extends Animal {}

public class Foo {
    public static void main(String[] args) {
        Animal[] animals = new Girafee[10];
        animals[0] = new Lion();
    }
}

我能做到这一点是因为:

  1. Java 在编译时不限制这一点(由于设计决定)
  2. 我有一个底层数组的引用,它允许我操作它的内部值

从外部谈论 class 的私有字段时,这并不成立。

例如,假设以下 class:

class Holder[+T](initialValue: Option[T]) {
  private[this] var value: Option[T] = initialValue
}

创建 Holder 的实例时,我对它的内部字段不可见,因此我无法像对 Java 数组那样直接操作它们。这样,编译器确保它们受到保护,并且对字段的每次操作都必须通过一个方法,其中类型检查器是严格的并且不允许时髦的业务。