init Block (Kotlin)

An init block contains initialization code that runs when an instance is created, as part of the primary constructor. It's where you put validation or setup that the primary constructor's parameter list can't express.

Kotlin

Kotlin's primary constructor has no body, so any logic that should run at construction goes in an init { } block. init blocks execute in the order they appear, interleaved with property initializers, right after the primary constructor parameters are available.

Common uses are validating arguments (require(age >= 0) { "age must be non-negative" }), deriving computed properties, and logging. The constructor parameters are in scope inside init, which is why you often initialize properties from them there.

A class can have several init blocks (run top to bottom) and secondary constructors that delegate to the primary one. Keep init logic light; heavy work in a constructor can surprise callers.

Syntax

class User(name: String) {
    init { require(name.isNotBlank()) }
}

Examples

Kotlin

class Temperature(val celsius: Double) {
    val fahrenheit: Double
    init {
        fahrenheit = celsius * 9 / 5 + 32
    }
}
println(Temperature(100.0).fahrenheit)

Output:

212.0

Learn it in a lesson

See also

Back to the Dictionary