I read that there is no package-private (default in Java) in scala and use public access by default.
What are the rationale for this choice? Is it a good practice as the default public access make everything visible, hence part of the API?
This means extra typing to encapsulate the fields and methods (whether it be private, scoped private, protected, access).
If a class member is public, no access modifier is required in the definition. In fact, Scala doesn't have a public keyword. This is the default access if we don't specify any modifier, and is equivalent to the Java public access.
The access level for class members and struct members, including nested classes and structs, is private by default.
Scala protected is different from protected in java. To mark a member protected, use the keyword protected before a class or variable. Protected members can be accessed only by the sub classes in the same package. Protected members cannot be accessed by other members in other packages even with imports.
In Scala, only a primary constructor is allowed to invoke a superclass constructor. In Scala, we are allowed to make a primary constructor private by using a private keyword in between the class name and the constructor parameter-list.
In Java it’s far easier to choose ‘package-private’ as the default because it is one out of only three possibilities there.
In Scala you can choose between public access (public
), package-private access with inheritance (protected[C]
), package-private access without inheritance (private[C]
), class-private access (private
), object-private access (private[this]
), inheritance access (protected
), protected[this]
access (whatever you may call it) and, additionally, you have some kind of file-private access modifier (sealed
).
It’s hard to select a default from that other than public
.
(Considering inner methods, one could also add method-private to the list…)
Scala has far more flexibility in choosing the visibility of something than Java, though some of Java visibility rules, related to nested classes are not translatable into Scala.
And, yes, there is package-private in Scala. It is written as private[package]
in Scala.
The reason why Scala makes public
the default is because it is the most common visibility used. The "extra typing" is actually less typing, because it is far more uncommon to make members private or protected.
One exception to that rule in Java is fields, which should be made private so one may be able to change details of implementation without breaking clients. One practical consequence of this are classes with fields and then getters and setters for each field.
In Scala, because one may be able to replace a val
or a var
with corresponding def
, this is not needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With