Start learning free

LESSON 634 OF 677 · OBJECT-ORIENTED PROGRAMMING

Access Modifiers in Scala

Lesson

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 private so 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.name is a compile error. Use rex.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.
privateVisible only inside the same class.
protectedVisible 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: Rex
STEP 1 OF 2
    Ctrl + Enter to check