Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Some of the reason for Scala having `private[this]` is that it allows an implementation that behaves (and performs) like a Java private field. Scala fields generally aren't raw fields at the JVM level (because of Scala's "uniform access principle" that `def x` should be accessible like `val x`), but private[this] fields allow the compiler to represent them as raw fields since they really can't be accessed elsewhere.

The only other thing I'm aware of being allowed to go in the[] part of a Scala access modifier is a containing package (or object?), which allows you to emulate Java's "default" (AKA "package-private") visibility.



That’s cool! Thanks for sharing, I had never considered that aspect of private[this].

Mentioned in the article, but it also powers covariant classes. In a language like C# only interfaces can have covariant type parameters, because it wouldn’t be sound to store a value in a (C#) private field if it had a covariant type. This influences a lot of the API design in C# where basically every container a covariant/immutable interface alongside the invariant/mutable implementation.

(Java gets around this with use site variance annotations which are more flexible but have their own drawbacks).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: