2

I'm currently looking how covariant and contravariant type parametrization is handled in Scala. And there's a special case, where a var field must be private[this] in order to compile. From example in this code snippet (taken in this question: private[this] vs private):

class Holder[+T] (initialValue: Option[T]) {
    // without [this] it will not compile
    private[this] var value = initialValue

    def getValue = value
    def makeEmpty { value = None }
}

I understand this example. But what I can't understand, is in what case is a private field accessible from another instance than itselt (this)?

Thanks for your help.

Community
  • 1
  • 1
Alain
  • 881
  • 8
  • 14

1 Answers1

5

If a member is plain-private, it is accessible from other instances of the same class. The [this] suffix makes it visible only to the instance that contains it.

David Harkness
  • 35,992
  • 10
  • 112
  • 134
  • Could you give me an example how an other instance of the same class accesses a plain-private member? I still don't get it... – Alain Dec 31 '12 at 15:02
  • 1
    They are common while implementing `equals`. Say you are to implement `equals` on your `Holder` class. One common approach is to do `def equals(that: Holder[T]) = (value == that.value)`. This code only compiles if `value` is made plain-private, because you are accessing `that.value` from the `this` instance (note that this is not the correct `Object.equals` signature, it is simplified for better understanding). – Rui Gonçalves Dec 31 '12 at 18:45