Lazy initialisation in Kotlin

Just like Late Initialisation lazy lets you initialise a property only when you need it, but it also remembers its value for future calls.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private val lazyValue: String by lazy {
    println("First hit")
    "Hello RealKotlin"
}

private val lazyValueWithoutThreadSafety: String by lazy(LazyThreadSafetyMode.NONE){
    "I am not synchronised"
}

fun consumeLazyValue(): Map<String, String> {
    return mapOf(
            "1st Request" to lazyValue,
            "2nd Request" to lazyValue
    )
}

fun consumeLazyValueUnsynchronised(): String {
    return lazyValueWithoutThreadSafety
}

fun main(args: Array<String>) {
    println(consumeLazyValue())
    // First hit
    // {1st Request=Hello RealKotlin, 2nd Request=Hello RealKotlin}

    for (i in 1..3) {
        println(consumeLazyValueUnsynchronised())
    }
    //I am not synchronised
    //I am not synchronised
    //I am not synchronised

}

lazy properties are also thread safe as they run in synchronized mode. If using lazy on the main thread and nowhere else, you may avoid the synchronized overhead by removing its thread safety. This mode should be used only when high performance is crucial and the lazy instance is guaranteed never to be initialised from more than one thread.

Updated: