Sobes.tech
Junior — Middle

Can you explain what the keyword lateinit means in Kotlin and in what cases it is used?

sobes.tech AI

Answer from AI

The lateinit keyword in Kotlin is used to declare variables that will be initialized later, but not at the moment of declaration. It is only applicable to var (mutable) variables and only for class properties, not for local variables.

The main purpose of lateinit is to avoid the need to initialize a variable immediately while not making it nullable. This is convenient when initialization depends on external factors, such as dependency injection or in Android when initializing components in the onCreate method.

Example:

class MyActivity : AppCompatActivity() {
    private lateinit var myTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        myTextView = findViewById(R.id.textView)
        myTextView.text = "Hello, world!"
    }
}

Trying to access a lateinit variable before it has been initialized will throw an UninitializedPropertyAccessException.

Thus, lateinit allows deferring the initialization of a variable while maintaining the convenience of working with non-nullable types.

Can you explain what the keyword lateinit means in… - sobes.tech