lateinit
- Kotlin course
- Beginner
- Lesson 81/116
- 5 min
Learn deferred initialization with lateinit var.
lateinit: late-initialized variable
Sometimes you want to initialize a variable later (for example during setup), not at the declaration. lateinit var enables this: the variable is declared but initialized later.
class Person {
lateinit var name: String
}
val p = Person()
p.name = "Ava" // now initialized
println(p.name)lateinit works only with var, non-null types and as a class property. Primitive types (Int, Double etc.) and val are not supported.
lateinit limits and isInitialized
Reading a lateinit variable before it is initialized throws UninitializedPropertyAccessException. You can check whether it was initialized with ::name.isInitialized.
class Person { lateinit var name: String }
val p = Person()
if (p::name.isInitialized) {
println(p.name)
} else {
println("not yet")
}This check is useful in test or iterative setup scenarios where you cannot be sure the variable has been initialized before.
Practice Init and print a lateinit Person
Define a class Person with a lateinit var name: String inside. In main create a Person, initialize p.name = "Ava", and print it with println(p.name).
Starter code
class Person {
// Define a lateinit String field called name
}
fun main() {
val p = Person()
// Initialize name with a value and print it
}Sample solution
class Person {
lateinit var name: String
}
fun main() {
val p = Person()
p.name = "Ava"
println(p.name)
}Expected output
Ava
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: lateinit
____ var name: String
lateinit var name: String
Explanation: lateinit var name: String is initialized later.
2 Which types cannot be used with lateinit?
- Primitive types like Int, Double Correct answer
- String
- List
- MutableList
Explanation: lateinit works only with non-null reference types; it does not support primitives like Int.
3 Match expression to role
| Term | Meaning |
|---|---|
lateinit var |
Late-initialized variable |
var |
Mutable (var) |
::name.isInitialized |
Is initialized? Boolean |
String (lateinit) |
Not nullable |