lateinit and Nullable Properties in Kotlin
Introduction
lateinit and Nullable Properties is a fundamental concept every Kotlin developer should understand. Null safety is one of Kotlin’s signature features. It catches null-related bugs at compile time instead of crashing at runtime with a NullPointerException.
Lateinit is used for non-nullable var properties that are initialized later. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- lateinit is used for non-nullable var properties that are initialized later.
- It applies only to mutable (var) properties of reference types.
- Use isInitialized to check whether a lateinit property has been assigned.
Syntax
lateinit var name: Stringlateinit and Nullable Properties in Kotlin Example Program in Kotlin
class User {
lateinit var username: String
}
fun main(args: Array<String>) {
val user = User()
user.username = "Thiyagaraaj"
println("Username: ${user.username}")
println("Initialized: ${user::username.isInitialized}")
}Sample Output
Username: Thiyagaraaj
Initialized: trueWhen to use
Use nullable types when a value may legitimately be absent — optional fields, parsed input, or database lookups that can miss.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
val user = User()assigns or updates a value used later in the program. -
user.username = "Thiyagaraaj"assigns or updates a value used later in the program. -
The
println("Username: ${user.username}")statement writes a line to the console — this produces part of the sample output below. -
The
println("Initialized: ${user::username.isInitialized}")statement writes a line to the console — this produces part of the sample output below. -
Lateinit is used for non-nullable var properties that are initialized later.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- lateinit is used for non-nullable var properties that are initialized later.
- It applies only to mutable (var) properties of reference types.
- Use isInitialized to check whether a lateinit property has been assigned.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.