TExcelTAD
Home › Kotlin › Kotlin Constructors

Kotlin Constructors

A constructor prepares a new object: it receives the initial values and makes sure the object starts in a valid state. Kotlin has a compact primary constructor in the class header, init blocks for setup code, and optional secondary constructors.

The primary constructor

kotlin · try it yourself
class Pet(val name: String, val species: String, var age: Int)

fun main() {
    val pet = Pet("Bella", "cat", 3)
    pet.age++
    println("${pet.name} the ${pet.species} is ${pet.age}")
}
Bella the cat is 4
Parameter form Becomes a property?
val name: String yes, read-only
var age: Int yes, mutable
name: String (no val/var) no — only usable in initializers and init

Default values and named arguments

Constructor parameters can have defaults and be passed by name, exactly like function parameters:

kotlin · try it yourself
class Pizza(val size: String = "medium", val cheese: Boolean = true, val toppings: List<String> = emptyList())

fun main() {
    val p1 = Pizza()
    val p2 = Pizza("large", toppings = listOf("olives", "basil"))
    val p3 = Pizza(cheese = false)

    println("${p1.size}, cheese=${p1.cheese}, ${p1.toppings}")
    println("${p2.size}, cheese=${p2.cheese}, ${p2.toppings}")
    println("${p3.size}, cheese=${p3.cheese}, ${p3.toppings}")
}
medium, cheese=true, []
large, cheese=true, [olives, basil]
medium, cheese=false, []

init blocks

The primary constructor can't contain statements, so setup logic goes into init blocks. They run in order, as part of construction. require is a neat way to validate arguments — it throws IllegalArgumentException if the condition is false:

kotlin · try it yourself
class Temperature(val celsius: Double) {
    val fahrenheit: Double

    init {
        require(celsius >= -273.15) { "Below absolute zero: $celsius" }
        fahrenheit = celsius * 9 / 5 + 32
        println("Created $celsius °C")
    }
}

fun main() {
    val t = Temperature(25.0)
    println(t.fahrenheit)
    try {
        Temperature(-300.0)
    } catch (e: IllegalArgumentException) {
        println("Error: ${e.message}")
    }
}
Created 25.0 °C
77.0
Error: Below absolute zero: -300.0

Properties computed from parameters

Plain constructor parameters (without val/var) can initialise other properties:

kotlin · try it yourself
class Rectangle(width: Int, height: Int) {
    val area = width * height
    val isSquare = width == height
}

fun main() {
    val r = Rectangle(4, 5)
    println("area=${r.area}, square=${r.isSquare}")
}
area=20, square=false

Here width and height aren't stored — r.width would be a compile error.

Secondary constructors

A secondary constructor is declared with constructor inside the class. If there's a primary constructor, each secondary one must delegate to it with : this(...):

kotlin · try it yourself
class Color(val red: Int, val green: Int, val blue: Int) {
    constructor(gray: Int) : this(gray, gray, gray)

    constructor(hex: String) : this(
        hex.substring(1, 3).toInt(16),
        hex.substring(3, 5).toInt(16),
        hex.substring(5, 7).toInt(16)
    )

    fun describe() = "rgb($red, $green, $blue)"
}

fun main() {
    println(Color(255, 128, 0).describe())
    println(Color(200).describe())
    println(Color("#7F52FF").describe())
}
rgb(255, 128, 0)
rgb(200, 200, 200)
rgb(127, 82, 255)

Tip: Default arguments make most secondary constructors unnecessary. Reach for constructor only when the alternative inputs are genuinely different (like a hex string vs. three numbers), or for Java interop.

Order of initialisation

When an object is created, Kotlin runs property initialisers and init blocks in the order they appear in the class body, then the body of the secondary constructor (if one was called).

Test yourself

Where do you put validation code that should run when an object is created?

  1. In the class header
  2. In an init block
  3. In main
  4. In a companion object

In class A(x: Int), is x a property you can read from outside?

  1. Yes
  2. No, it is only a constructor parameter
  3. Only if it is an Int
  4. Only inside main

What must a secondary constructor do when the class has a primary constructor?

  1. Nothing special
  2. Delegate to it with : this(...)
  3. Call super()
  4. Be private