Start learning free

LESSON 287 OF 677 · FUNCTIONS & CLASSES

Constructors in Kotlin

Lesson

TL ; DR:

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


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

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

  • Then create objects with arguments: 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 = 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 Dog(...) is called.


Defining a constructor

A Kotlin constructor has two distinguishing features:

  • It is declared with the constructor keyword inside the class.

  • It has no return type — not even Unit.

constructor(name: String, age: Int) {
    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  = Dog("Rex", 4)
val luna = 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, Kotlin provides a hidden no-arg one for free — that's why Dog() worked in earlier lessons. The moment you define your own constructor, that freebie disappears: from now on you must call Dog with the arguments you specified.


Primary constructors:

The form above is a secondary constructor. In everyday Kotlin you will more often see the primary constructor, declared right in the class header. Marking a parameter val (or var) there also creates the property — it declares, stores, and exposes the value in one line:

class Dog(val name: String, var age: Int)

val rex = Dog("Rex", 4)
println(rex.name) // Rex

That single line does the same work as the field declarations plus the constructor block above.


Your task

Declare the Dog class with a primary constructor that takes var name: String and var age: Int, so no this assignments are needed. Then in mainFunction, create two dogs:

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

Expected output:

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