Change `private` to mean `private[this]`?

On proper use of protected.

It is useful in two cases,

  • access to objects (static methods in Java). In the package. That’s weird as the author doesn’t know every class in the package. They usually know enough, so it’s good enough.
  • declaring a contract that is only for the subclass.

In other words, it is never valid for implementation details. The author must use private for any implementation methods.

WIP pull request, looking good I think: https://github.com/scala/scala/pull/8286

2 Likes

This looks very interesting! It would be great if we could avoid accessors for private fields.

In fact, if this works out, it looks attractive to scrap private[this] and protected[this] altogether. private[this] has become next to pointless then. Yes, it communicates that a field is accessed only from this, but this can also be trivially established by just searching all occurrences of the field in the class. Visibility modifiers establish a contract between a class member and its users. Here there’s not contract to establish since everything stays in a single class.

The original purpose of protected[this] was to provide more relaxed constraints for type parameter variance. These constraints have been shown to be unsound, so in Scala 3 protected[this] behaves exactly like protected wrt variance. I don’t think there is a point to keep it anymore.

Eliminating [this] would provide a real language simplification by dropping a syntax construct from the language,

7 Likes

Doesn’t private[this] also affect variance? private vars cannot have types which are covariant type parameters of the enclosing class for example, while private[this] vars can

1 Like

Yes, private[this] does affect variance. But the compiler can figure out that access to a private member is always via this and apply the looser variance rule in that case; it does not need an annotation to know that.

1 Like

Personally I never needed a private which isn’t actually private[this]. And in fact, despite the noise, I always write private[this] for vals in order to avoid the accessor as mentioned. I don’t do it for defs because I don’t think there’s any advantages - or at least I didn’t see any difference at the bytecode level.

4 Likes

The thread continues in https://contributors.scala-lang.org/t/proposal-to-retain-private-this-in-scala-3

2 Likes