Sobes.tech
Middle

What are 'lazy' and 'lateinit' in Kotlin?

sobes.tech AI

Answer from AI

lazy - a property delegate for deferred initialization of immutable (read-only) properties (val). The value is computed upon the first access to the property and then cached.

// Example of using lazy
val lazyValue: String by lazy {
    println("Initialization") // will be printed only once upon first access
    "Hello, lazy!"
}

lateinit - a modifier for mutable (var) properties that allows deferring initialization until the first access. The property must be non-nullable. Using the property before initialization results in an UninitializedPropertyAccessException.

// Example of using lateinit
lateinit var lateinitVariable: String

fun initializeVariable() {
    lateinitVariable = "Hello, lateinit!"
}

fun useVariable() {
    // Optional check for initialization before use
    if (::lateinitVariable.isInitialized) {
        println(lateinitVariable)
    } else {
        println("Variable is not initialized yet")
    }
}

Main differences:

Feature lazy lateinit
Property type val (read-only) var (mutable)
Nullability Can be nullable or non-nullable Must be non-nullable
Initialization Automatic, upon first access Manual
Deferred Yes, computed upon first access Yes, declared without initialization
Thread safety Thread-safe by default (synchronization), with options Not guaranteed, depends on context
Exception on access before initialization No, initialized automatically UninitializedPropertyAccessException
What are 'lazy' and 'lateinit' in Kotlin? — Kotlin - sobes.tech