Kotlin

init Block + Constructor Order

admin by @admin ADMIN
1h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`init { }` blocks run during construction, in declaration order, interleaved with property initializers. Use to validate the primary constructor or set up derived state.
Kotlin
Raw
class User(name: String, age: Int) {
    val name: String
    val age: Int
    val createdAt: Long = System.currentTimeMillis()         // initializer runs in order

    init {                                                   // first init block
        require(name.isNotBlank()) { "name required" }
        require(age >= 0)          { "age must be >= 0"  }
    }

    val displayName: String = "@${name.lowercase()}"         // initializer between init blocks

    init {                                                   // second init block
        println("created user $displayName at $createdAt")
    }

    init {
        this.name = name.trim()
        this.age  = age
    }
}

// Secondary constructors — must delegate to primary
class Account(val email: String, val plan: String) {
    constructor(email: String) : this(email, "free") {       // delegates to primary
        println("created with default plan")
    }
}

fun main() {
    val u = User("Alice", 30)
    val a = Account("a@x.com")                               // uses secondary
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.