Access modifiers in Scala control the visibility and accessibility of classes, objects, and their members. They play a crucial role in encapsulation, a fundamental principle of object-oriented programming.
Scala provides three main access modifiers:
Public is the default access level in Scala. Members without any explicit modifier are public and can be accessed from any code.
class Person {
val name = "Alice" // Public by default
def greet() = println(s"Hello, $name!")
}
Private members are only accessible within the class or object that contains their definition. This is useful for hiding implementation details.
class BankAccount {
private var balance = 0.0
def deposit(amount: Double): Unit = {
balance += amount
}
}
A more restrictive form of private is private[this]
, which limits access to the current instance of the class.
Protected members can be accessed within the class and its subclasses. This is useful for allowing inheritance while still restricting general access.
class Animal {
protected def breathe(): Unit = println("Breathing...")
}
class Dog extends Animal {
def live(): Unit = {
breathe() // Accessible in subclass
println("Dog is living")
}
}
Scala also allows you to specify access at the package level using the private[package]
syntax.
Access modifiers are closely related to other Scala concepts:
Understanding access modifiers is crucial for writing well-structured, maintainable Scala code. They help in creating clear boundaries between public interfaces and private implementations, enhancing the overall design of your Scala applications.