Normally, properties declared as having a non-null type must be initialised in the constructor. However, fairly often this is not convenient. For example, properties can be initialised through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initialiser in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.
To handle this case, you can mark the property with the lateinit modifier.
The modifier can be used on var properties declared inside the body of a class (not in the primary constructor, and only when the property does not have a custom getter or setter) and, since Kotlin 1.2, for top-level properties and local variables. The type of the property or variable must be non-null, and it must not be a primitive type.
Accessing a lateinit property before it has been initialised throws a special exception that clearly identifies the property being accessed and the fact that it hasn’t been initialised.
class MainActivity : AppCompatActivity() {
private lateinit var tvDescription: TextView // We don't want to set the value yet but we'd also prefer to not set to nullable. Use lateinit to let compiler know you will initialise it later
// N.B. If you don't initialise it the IDE will not warn you and you'll get a kotlin.UninitializedPropertyAccessException at runtime
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tvDescription = findViewById(R.id.tv_description)
tvDescription.text = "Refreshing glass of water gets you hydrated"
}
}
