Constructors and init blocks

suggest change

In Kotlin, class instantiation is designed around a single concise primary constructor, supplemented by init blocks for validation or initialization logic, and optional secondary constructors when multiple instantiation forms are required.


Primary Constructor

The primary constructor is declared directly in the class header following the class name. If parameters are prefixed with val or var, Kotlin automatically creates corresponding properties:

// Declares properties 'name' (read-only) and 'age' (mutable)
class User(val name: String, var age: Int)

// Parameters without val/var are constructor arguments, not properties
class Rectangle(width: Double, height: Double) {
    val area: Double = width * height
}

If the primary constructor requires annotations or visibility modifiers, the constructor keyword is mandatory:

class SecureToken private constructor(val rawToken: String) {
    companion object {
        fun generate(): SecureToken = SecureToken(java.util.UUID.randomUUID().toString())
    }
}

init Blocks

Because the primary constructor header cannot contain executable statements, initialization code is placed inside one or more init blocks.

init blocks have access to constructor parameters (even those not declared as val or var):

class BankAccount(val accountNumber: String, initialBalance: Double) {
    var balance: Double = 0.0
        private set

    init {
        require(accountNumber.isNotBlank()) { "Account number cannot be blank." }
        require(initialBalance >= 0.0) { "Initial balance must not be negative." }
        this.balance = initialBalance
        println("BankAccount $accountNumber created with balance $$balance")
    }
}

Initialization Order

During class instantiation, property initializers and init blocks execute in the exact order they appear in the class body:

class InitDemo(name: String) {
    val firstProperty = "First: $name".also(::println)

    init {
        println("First init block executed")
    }

    val secondProperty = "Second: ${name.length}".also(::println)

    init {
        println("Second init block executed")
    }
}

// Creating InitDemo("Kotlin") prints:
// First: Kotlin
// First init block executed
// Second: 6
// Second init block executed

Secondary Constructors

Secondary constructors are declared within the class body using the constructor keyword. If the class has a primary constructor, every secondary constructor must delegate to the primary constructor (either directly via : this(...) or indirectly through another secondary constructor).

class Person(val name: String, val age: Int) {
    // Secondary constructor 1: defaults age to 0
    constructor(name: String) : this(name, age = 0) {
        println("Secondary constructor (name only) called")
    }

    // Secondary constructor 2: takes fields of a parsed CSV line
    constructor(csvFields: List<String>) : this(
        name = csvFields[0],
        age = csvFields[1].trim().toInt()
    ) {
        println("Secondary constructor (csvFields) called")
    }
}

Note: In modern Kotlin, default parameter values usually eliminate the need for secondary constructors. Prefer class Person(val name: String, val age: Int = 0) over overloaded secondary constructors.


Inheritance and Constructor Execution Order

When inheriting from a base class, base class initialization always runs before derived class initialization logic.

open class Base(val label: String) {
    init {
        println("Base init: label = $label")
    }
}

class Derived(label: String, val count: Int) : Base(label) {
    init {
        println("Derived init: count = $count")
    }
}

fun main() {
    Derived("Sample", 10)
}
// Output:
// Base init: label = Sample
// Derived init: count = 10

Critical Caveat: Calling Open Members in Constructors

Never invoke open methods or access open properties inside a base class constructor or init block. In Kotlin, the base class constructor runs before the derived class properties have been initialized:

open class Vehicle {
    open val wheels: Int = 4

    init {
        // DANGEROUS: prints 0 because Subclass wheels has not initialized yet!
        println("Vehicle initialized with $wheels wheels")
    }
}

class Bicycle : Vehicle() {
    override val wheels: Int = 2
}

fun main() {
    Bicycle() // Prints: Vehicle initialized with 0 wheels!
}

Best Practices

  1. Prefer Primary Constructors with Defaults: Use default parameter values instead of declaring multiple secondary constructors.
  2. Validate Arguments in init Blocks: Use require(...) or check(...) inside init to enforce class invariants immediately on instantiation.
  3. Avoid Complex Logic in init: Keep init blocks lightweight. Avoid I/O, network requests, or starting threads inside constructors.
  4. Use Factory Functions for Complex Instantiation: If object construction requires asynchronous loading or conditional subtype selection, make the constructor private and provide a companion object factory function:
    class Config private constructor(val settings: Map<String, String>) {
        companion object {
            suspend fun loadFromFile(file: File): Config {
                val data = withContext(Dispatchers.IO) {
                    file.readLines().associate { it.substringBefore("=") to it.substringAfter("=") }
                }
                return Config(data)
            }
        }
    }
    

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents