Late initialisation in Kotlin

Non-null type properties must be initialised in the constructor but that’s not always very convenient. lateinit properties change that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private lateinit var name: String

fun getMessage(): String {
    name = "RealKotlin"
    val message = "We didn't even need to say $name until now"
    // lateinit properties are always mutable. Be careful!
    name = "42"
    return message
}

fun getNewMessage(): String = name

fun main(args: Array<String>) {
    println(getMessage())
    // We didn't even need to say RealKotlin until now

    println(getNewMessage())
    // 42
}

Whenever you need a mutable property or one that is set outside of your class, lateinit may be just what you need.

Updated: