Thuta Learning
Kotlin
IntermediateProgrammingBeginner

Constructors

KotlinLesson 1530 min

What you'll walk away with

  • Declare a primary constructor and tell constructor parameters from properties (val/var)
  • Predict the order in which property initializers and init blocks run
  • Use default and named arguments instead of piles of overloads
  • Write secondary constructors that delegate with this(...) and hide a constructor behind a factory function

Explain it simply

Explain it simply

A constructor is the moment an object is born. When you write Person("John", 35) you hand over the information the new object needs before anybody can use it, much like filling in a form before it is filed. Kotlin lets you write the form fields straight after the class name, which is why many Kotlin classes fit on a single line.

The parameters in that header are only the paperwork. Putting val or var in front of one also turns it into a property that stays on the object. Without val or var, the value is visible while the object is being built and then gone.

Problem → Why → Solution

The problem: half-built objects

Without constructor parameters, creating an object and filling it in become two separate steps. You call Person() and then set the fields one by one. Forget one and you hold an object with a blank name, nothing stops age = -5, and every place that creates a Person repeats the same setup lines.

half-built.kt
class Person {
    var firstName: String = ""
    var age: Int = 0
}

fun main() {
    val p = Person()
    p.age = -5                          // nothing stops this
    println("'${p.firstName}' is ${p.age}")   // '' is -5
}

Why is optional setup not enough?

An object that can exist half-built forces every reader of the object to check whether it is valid. A constructor makes validity a precondition of existence: if Person("", -5) is rejected inside init, no Person with a blank name can ever exist. Callers have fewer checks to make, and the rules for what a valid Person is sit next to the class instead of being repeated everywhere.

Core concept: the header, init blocks and the order

The primary constructor lives in the class header: class Person(val firstName: String, var age: Int). A parameter with val or var is also a property. A parameter with neither is a plain parameter: you can use it in property initializers and init blocks, and after that it is gone. The constructor keyword is only needed when there is a modifier or annotation, as in class Port private constructor(...).

A header cannot hold code, so validation and setup go into init blocks. Property initializers and init blocks run top to bottom in the order they appear in the class body, and you may write more than one init block. Using a property inside an init block before its declaration gives an error such as "variable 'area' must be initialized". Rejecting bad input with require(condition) { message } throws IllegalArgumentException and no object is created.

Default and named arguments replace the piles of overloads you may know from Java. With city: String = "Yangon", both Person("Aye", 30) and Person("Aye", 30, "Mandalay") work. Named arguments can be written in any order, as in Person(city = "Mandalay", age = 41, firstName = "Kyaw"), and they protect you from passing two Strings in the wrong order.

Secondary constructors are written with the constructor keyword, and when a primary constructor exists they must delegate to it with this(...), directly or through another secondary constructor. Otherwise you get "primary constructor call expected". The delegate runs first, including the primary constructor's init blocks, and only then does the secondary constructor's own body run. Prefer default arguments when they are enough, and keep secondary constructors for genuinely different input shapes, such as building a user from an email address.

Parameter styleBecomes a property?Visible where
name: StringNoHeader, init blocks, property initializers
val name: StringYes, read-onlyEverywhere the class is visible
var name: StringYes, read-writeEverywhere, and writable
private val name: StringYes, privateInside the class only
Mental model: paperwork first, then the object
  1. Caller passes arguments to the header
  2. Initializers and init blocks run in order
  3. A secondary body runs after its delegate
  4. The finished object is handed back

If a require inside init fails, no object comes out, so every object that exists has passed the checks.

General pattern

kotlin
class ClassName(
    val readOnly: Type,
    var editable: Type,
    plainParam: Type,
    val withDefault: Type = defaultValue,
) {
    init { /* validate, e.g. require(condition) { "message" } */ }

    constructor(other: Type) : this(arg1, arg2, arg3)
}

Each header parameter can be val, var or neither, and may carry a default value. The init block is for validation. constructor(...) : this(...) is a second way in that hands the work back to the primary constructor.

Example: a Person with two properties declared in the header

The whole class is one line. The header lists the data every Person needs, and val and var decide which parts may change later. main supplies both values in order and reads the two properties back inside a template. Then rewrite the call as Person(firstName = "John", age = 35); the result is identical.

kotlin
class Person(val firstName: String, var age: Int)

fun main() {
    val person = Person("John", 35)
    println("${person.firstName} is ${person.age} years old.")
}

Code breakdown

  1. Header and class in one lineclass Person(val firstName: String, var age: Int)

    The primary constructor sits right beside the class name. No body is needed, so there are no braces. The header tells the compiler that building a Person requires both a firstName and an age.

  2. A read-only propertyval firstName: String

    Because of val, firstName is a read-only property with only a getter. person.firstName = "x" would not compile, which declares that a name never changes after construction.

  3. A read-write propertyvar age: Int

    var gives age both a getter and a setter. After construction it can still change, for example person.age += 1 on every birthday. Use var only for data that really changes.

  4. Call with positional argumentsPerson("John", 35)

    Arguments pair up with header parameters in order: "John" goes to firstName and 35 goes to age. If someone reorders the parameters, positional calls like this can break without any message, which is why named arguments are safer.

  5. Read both propertiesprintln("${person.firstName} is ${person.age} years old.")

    The template reads both properties through their getters. Without val or var in the header, person.firstName would be an "unresolved reference 'firstName'" error.

You should see
John is 35 years old.
What happens when you call Person("John", 35)
  1. Person("John", 35) is called
  2. Arguments are bound to the header parameters
  3. Property initializers and init blocks run top to bottom
  4. Did every check in init pass?

All checks pass

the finished Person is returned

A require fails

IllegalArgumentException is thrown and no Person exists

init blocks, defaults and named arguments

The class below has two init blocks with a property initializer between them. The order is top to bottom: the first init prints and rejects bad input, then label is computed, and only then can the second init see label. Move the second init above label and it no longer compiles, because label would not exist yet. main shows three calls: one using the default city, one with named arguments in any order, and one where require rejects a blank name.

init-order.kt
class Person(val firstName: String, val age: Int, val city: String = "Yangon") {
    init {
        println("init A: $firstName")
        require(firstName.isNotBlank()) { "firstName must not be blank" }
        require(age in 0..150) { "age out of range: $age" }
    }

    val label: String = "$firstName ($age) from $city"

    init {
        println("init B: $label")
    }
}

fun main() {
    val a = Person("Aye", 30)
    println(a.label)
    val b = Person(city = "Mandalay", age = 41, firstName = "Kyaw")
    println(b.label)
    try {
        Person("  ", 20)
    } catch (e: IllegalArgumentException) {
        println("rejected: " + e.message)
    }
}

Secondary constructors and delegation

The User class has three constructors. The primary one needs every value. The first secondary fixes active to true and prints a message from its own body. The second secondary takes only an email address and uses the part before @ as the name. Watch the order: User("zaw@example.com") delegates twice, so it also triggers the first secondary's message. And whichever constructor you enter through, init blocks and property initializers run exactly once, as part of the primary constructor.

secondary.kt
class User(val name: String, val email: String, val active: Boolean) {
    constructor(name: String, email: String) : this(name, email, true) {
        println("secondary ran for $name")
    }

    constructor(email: String) : this(email.substringBefore("@"), email)
}

fun main() {
    val a = User("Aye", "aye@example.com", false)
    val b = User("Kyaw", "kyaw@example.com")
    val c = User("zaw@example.com")
    println("${a.name} ${a.active}")
    println("${b.name} ${b.active}")
    println("${c.name} ${c.active}")
}

Private constructors and factory functions

Sometimes the right answer to bad input is not an exception but the result "cannot be built". A constructor can only return an object, never null, so you make the constructor private and expose a factory function in the companion object. Port.parse("8080") returns a Port, while "99999" and "web" return null, and the caller handles the null. With this pattern an invalid Port can never exist.

factory.kt
class Port private constructor(val number: Int) {
    companion object {
        fun parse(text: String): Port? {
            val n = text.toIntOrNull() ?: return null
            return if (n in 1..65535) Port(n) else null
        }
    }
}

fun main() {
    println(Port.parse("8080")?.number)
    println(Port.parse("99999"))
    println(Port.parse("web"))
}

In real projects

Where this shows up in real projects

In real projects the constructor is the main door for dependencies. Writing class OrderService(private val repository: OrderRepository) makes it explicit that whoever builds the service must supply a repository, and a test can pass a fake in place of the real one. Frameworks such as Spring and Hilt read constructor parameters to know what to supply on your behalf.

Settings and request objects can be declared with one constructor full of default arguments, which removes the long builder classes Java needs. You write only what you want to change, as in HttpClientConfig(timeoutSeconds = 5). Data that arrives from outside the program, a form, JSON or the command line, is usually checked once by a factory such as Port.parse, and the rest of the code then handles only valid objects.

Common mistakes

Common mistakes

1. Forgetting val or var in the header

In class Person(firstName: String, var age: Int), firstName is not a property, so person.firstName fails with "unresolved reference 'firstName'". Add val or var when outsiders should read it; leaving both off is correct when only the constructor needs it.

2. Passing same-typed arguments in the wrong order

User("aye@example.com", "Aye") compiles even though name and email are swapped, because both are Strings, and the data is silently wrong. When a call has two or more parameters of the same type, use named arguments such as User(name = ..., email = ...).

3. Using a property in init before it is declared

Writing init { println(area) } above val area = width * 2 gives "variable 'area' must be initialized", because init blocks and initializers run in the order they appear. Move the init block below the properties it uses.

4. A secondary constructor that does not delegate

In a class with a primary constructor, constructor(name: String, email: String) { ... } without a this(...) call fails with "primary constructor call expected". Every secondary constructor must reach the primary one through this(...).

Best practices

Best practices

  • Validate in init with require so an invalid object can never exist.
  • Prefer default arguments over several secondary constructors.
  • Use named arguments at the call site when two parameters share a type or the call has more than three arguments.

Mini challenge

Mini challenge: a Rectangle class

Write a Rectangle class that refuses invalid sizes and offers a second constructor for squares.

  • Declare width and height as read-only properties in the primary constructor
  • In an init block, reject non-positive sides with require; the message looks like sides must be positive, got 0x2
  • Add a secondary constructor so that Rectangle(side) builds a square
  • Expose area and perimeter as properties with getters, and in main use a named-argument call and catch the rejection
rectangle.kt
class Rectangle(/* TODO: width and height as read-only properties */) {
    // TODO: init block: require both sides to be positive
    // TODO: constructor(side: Int) that delegates to the primary one
    // TODO: area and perimeter as properties with getters
}

fun main() {
    // TODO: build Rectangle(width = 4, height = 3) and Rectangle(5)
    // TODO: print "area perimeter" for each, for example "12 14"
    // TODO: catch the exception for Rectangle(0, 2) and print its message
}

Expected: The program prints these three lines: 12 14 25 20 sides must be positive, got 0x2

Show hint

Write the secondary constructor as constructor(side: Int) : this(side, side). The message uses a template such as "sides must be positive, got ${width}x$height". Catch the failure with catch (e: IllegalArgumentException) and print e.message.

Show solution
rectangle.kt
class Rectangle(val width: Int, val height: Int) {
    init {
        require(width > 0 && height > 0) {
            "sides must be positive, got ${width}x$height"
        }
    }

    constructor(side: Int) : this(side, side)

    val area: Int
        get() = width * height

    val perimeter: Int
        get() = 2 * (width + height)
}

fun main() {
    val r = Rectangle(width = 4, height = 3)
    val s = Rectangle(5)
    println("${r.area} ${r.perimeter}")
    println("${s.area} ${s.perimeter}")
    try {
        Rectangle(0, 2)
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }
}

Quick quiz 1 / 3

Given class Person(firstName: String, var age: Int), what happens with println(Person("Aye", 30).firstName)?

Quick quiz 2 / 3

Creating T() from class T { init { println("A") }; val x = show("B"); init { println("C") } }, what is the print order (show prints its argument)?

Quick quiz 3 / 3

In a class that has a primary constructor, what must every secondary constructor do?

What to remember

  • The primary constructor lives in the class header; a val or var parameter is also a property, and a plain parameter is visible only during construction.
  • Property initializers and init blocks run top to bottom in the order written, and a require inside init refuses to build an invalid object.
  • Default and named arguments replace piles of overloads and guard against swapping same-typed parameters.
  • A secondary constructor must delegate with this(...); when rejection should mean null, use a private constructor and a companion factory.

Kotlin language guide — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Constructors | Thuta Learning