Start learning free

LESSON 185 OF 348 · OBJECT-ORIENTED PROGRAMMING

Access Modifiers in Scala in Scala

Lesson

TL ; DR:

  • An access modifier controls who can see a member of a class. The two you'll use most are public (anyone) and 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 var name: String = ""
    
        public Dog(String name) {
            this.name = name
        }
    
        def getName() {
            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. 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 Double balance

    def deposit(Double amount) {
        if (amount < 0) throw new IllegalArgumentException()
        balance += amount
    }
}

The four Scala modifiers

publicVisible everywhere.
privateVisible only inside the same class.
protectedSame package + subclasses.
(no modifier)Package-private — only the same package.

For now, focus on 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

    Access Modifiers in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free