How to fix 'illegalstateexception: x must not be null' in kotlin?

This error indicates that you're trying to access a non-nullable property before it has been initialized.

Example:


lateinit var name: String

fun main() {
    println(name)
}

Solution:


lateinit var name: String

fun main() {
    name = "John"
    println(name)
}
Ensure that `lateinit` properties are initialized before they're accessed.

Beginner's Guide to Kotlin