开发者

Default public access in scala

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 p开发者_开发技巧rivate, protected, access).


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.


This is something that gives a lot of people some trouble. I'd suggest giving this entry (actually the entire series) a read.

Immutability also prevents any of the funnies that generally occur with such access. It might be true that "there is more typing", but looking at IDEs, they are responsible for a lot of fud as any generated method by the IDE is usually public, which is not always valid either.


According to Programming Scala, it seems like the default public is mainly due to the uniform access principle, where operator overloading allow one to define the getter as field = newvalue

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜