๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Lateinit

lateinit is a modifier that lets a var start with no value and receive its value during setup.

A value that arrives later

Greeter is created before name is known. The ready check reads false first and true after the set.

class Greeter {
    lateinit var name: String

    fun ready(): Boolean {
        return ::name.isInitialized
    }

    fun greet() {
        println("Hello, $name")
    }
}

fun main() {
    val g = Greeter()
    println(g.ready())
    g.name = "Bo"
    println(g.ready())
    g.greet()
}

Setup fills the value in

The load function plays the setup role here. It sets city before show reads it.

class Profile {
    lateinit var city: String

    fun load() {
        city = "Lisbon"
    }

    fun show() {
        println(city)
    }
}

fun main() {
    val p = Profile()
    p.load()
    p.show()
}

lateinit on a val fails

name is declared with val here, so lateinit has no mutable property to attach to. The compiler stops on the lateinit line.

class Greeter {
    lateinit val name: String
}

fun main() {
    val g = Greeter()
    println(g.name)
}

Example

class Session {
    lateinit var user: String

    fun signIn(name: String) {
        user = name
    }

    fun status(): String {
        return if (::user.isInitialized) "signed in as $user" else "no user yet"
    }
}

fun main() {
    val s = Session()
    println(s.status())
    s.signIn("Ana")
    println(s.status())
}

Key points

  • lateinit marks a var whose value arrives after the object is created.
  • The property starts with no value at all.
  • Setup code sets the value before any other code reads the property.
  • Inside the class, ::name.isInitialized reports whether name has been set yet.
  • lateinit works on String and class types, not on Int or Boolean.

In this example, the Session starts with no user set. The first status call reads the isInitialized check as false and reports no user yet. After signIn sets the lateinit var, the same check reads true.

Note

a val cannot carry lateinit, and the compiler rejects that shape.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does ::name.isInitialized return before any value is set?