Start learning free

LESSON 598 OF 639 · OBJECT-ORIENTED PROGRAMMING

Getters and Setters in Scala in Scala

Lesson

TL ; DR:

A getter reads a private field. A setter changes it, but only to a value the class allows.

In Scala, the getter is a method def age, with no parentheses. The setter is a method named age_=. With both, other code writes rex.age = 4, as if age were a field.


class Dog(private var _age: Int) {
    def age: Int = {
        return _age
    }

    def age_=(value: Int): Unit = {
        if (value >= 0) {
            _age = value
        }
    }
}


Full lesson:

In the Access Modifiers lesson, the field was private and getName() read it. Scala lets a getter and a setter look like a field from outside.

The getter

The private field needs a different name. Here it is _age, a class parameter. The method age returns it, so reading rex.age calls it.

The setter

The setter is named like the getter, plus _=. Scala turns rex.age = 4 into the call rex.age_=(4). This works only when a getter with the same name exists.

The rule

A dog's age can't be negative. So the setter changes _age only when value is 0 or more. After rex.age = -5, the age stays as it was.

Why not a public field?

With a public var age, any code could set it to -5. Nothing would check it. The setter keeps the rule inside the class. The code that uses rex.age stays the same.


Your task

The Dog class keeps its age in the private _age. Add a getter age that returns it. Add a setter age_= that ignores negative values.

The code in mainFunction creates rex, then reads and sets rex.age.

Expected output:

Rex is 3
Rex is still 3
Rex is 4
STEP 1 OF 3
    Ctrl + Enter to check

    Getters And Setters in Scala

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