Start learning free

LESSON 182 OF 348 · OBJECT-ORIENTED PROGRAMMING

Constructors in Scala in Scala

Lesson

TL ; DR:

  • A constructor is a special method that runs automatically when you create an object with new. It's used to set up the object's initial state.


  • In Scala, a constructor sets up the object's fields when it is created:

    class Dog {
        var name: String = ""
        var age: Int = 0
    
        def this(name: String, age: Int) = {
            this()
            this.name = name
            this.age = age
        }
    }
    

  • Then create objects with arguments: new Dog("Rex", 4) — the constructor fills in the fields for you.



Full lesson:

In the previous lesson you set fields after creating the object:

val dog = new Dog()
dog.name = "Rex"
dog.age = 4

That works, but it's noisy and easy to forget. Constructors let you initialize the fields the moment new Dog(...) is called.


Defining a constructor

A Scala auxiliary constructor has two distinguishing features:

  • It is declared with def this inside the class.

  • It has no return type — not even Unit.

def this(name: String, age: Int) = {
    this()
    this.name = name
    this.age = age
}

The this keyword

The parameter name and the field name have the same identifier. Without this, both sides of name = name would refer to the parameter (the local one wins). this is a built-in reference to "the current object", so this.name is the field, and bare name is the parameter.


Calling the constructor

val rex  = new Dog("Rex", 4)
val luna = new Dog("Luna", 7)

By the time these lines finish, rex.name is already "Rex", rex.age is 4, and the same for Luna.


The default constructor

If you don't write any constructor, Scala provides a hidden no-arg one for free — that's why new Dog() worked in earlier lessons. The moment you define your own constructor, that freebie disappears: from now on you must call new Dog with the arguments you specified.


Your task

The Dog class already has the name and age fields. Add a constructor that takes a name: String and an age: Int and assigns them using this. Then in mainFunction, create two dogs:

val rex  = new Dog("Rex", 4)
val luna = new Dog("Luna", 7)

Expected output:

Rex is 4
Luna is 7
STEP 1 OF 2
    Ctrl + Enter to check

    Constructors 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