Scala/Access modifiers

From Wikibooks, open books for an open world
Jump to navigation Jump to search

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

[edit | edit source]

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


[edit | edit source]

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.


[edit | edit source]

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

class StopWatch {
  //INVARIANT: "seconds" is 0 or positive (assuming no overflows).
  private var seconds = 0
  def addSeconds(secondsAmount:Int) {
    if (secondsAmount > 0) {
      seconds += secondsAmount
  def currentSeconds = seconds
val stopWatch = new StopWatch
println("Seconds: " + stopWatch.currentSeconds) //Prints "Seconds: 0".
println("Seconds: " + stopWatch.currentSeconds) //Prints "Seconds: 5".
//ERROR: Does not compile!
//stopWatch.seconds = -10

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.


[edit | edit source]

Scope of access modifiers

[edit | edit source]

Companion objects

[edit | edit source]