Scala/Access modifiers

Scala provides several access modifiers. Access modifiers can be used to change in which contexts the members of classes, objects, traits and packages can be accessed. Limiting access to members can help separate interface from implementation, ensure and verify invariants and preserve the integrity of members.

Access modifiers
An access modifier changes when a member can be referenced. Attempts at referencing an in-accessible member causes a compile-time error.

Public
The default access modifier for members is the "public" access modifier. Members with "public" access can be accessed from anywhere. There is no keyword for "public" access.

Private
The "private" access modifier prevents access anywhere outside the scope of the member's definition:

A class named "StopWatch" is defined in the first part. The first member definition of the class is "private var seconds = 0". The keyword "private" is used before the "var" declaration to indicate that the following variable, here "seconds", has private access. This means that it can only be accessed inside the scope of its containing class, "StopWatch". The methods "addSeconds" and "currentSeconds" respectively modifies and retrieves "seconds". Note that "addSeconds" prevents negative values from being added to "seconds". The lines following the class definition instantiates an instance of the class "StopWatch", and calls the different methods. It is not possible to subtract from "seconds" using the "addSeconds" method, and attempts at manipulating "seconds" by directly referring to it outside of "StopWatch" fails at compile-time. Thus, the invariant that requires that "seconds" is 0 or positive is always obeyed, assuming no overflows.