TL ; DR:
An access modifier controls who can see a member of a class. In Scala a member is public (anyone can use it) unless you mark it
private(only this class).Make data
privateso callers can't break invariants. Expose what they need through public methods (often called getters and setters):class Dog(private val name: String) { def getName(): String = { return name } }
Outside the class,
rex.nameis a compile error. Userex.getName()instead.
Full lesson:
So far every field we wrote was public (Scala has no public keyword; it is the default). That's convenient, but leaks internals. If you later decide to validate or compute the value differently, every caller in the codebase breaks.
Encapsulation
Encapsulation is the idea that an object's data should be hidden behind methods. The class controls how it's read and written; outside code only sees the API.
class Account {
private var balance: Double = 0.0
def deposit(amount: Double): Unit = {
if (amount < 0) throw new IllegalArgumentException()
balance += amount
}
}
The Scala access levels
| (no modifier) | Public — visible everywhere. |
private | Visible only inside the same class. |
protected | Visible inside the class and its subclasses. |
For now, focus on the default (public) and private.
Your task
The Dog class's name field is now private. Add a def getName() method that returns it.
Dog's name: RexFree plan: 30 tutor messages. PRO is unlimited.
