通常,一个变量在被用到之前不需要初始化,而占用内存。
lateinit var diceImage : ImageView
The lateinit keyword promises the Kotlin compiler that the variable will be initialized before the code calls any operations on it.
用了 lateinit 关键字,可以保证变量不用先初始化,但在用到它的时候会初始化。
用 lateinit 的方法可以代替下面这个方法:
// 不太好的示范
var diceImage : ImageView? = null
Therefore we don't need to initialize the variable to null here, and we can treat it as a non-nullable variable when we use it.
相比用先初始化一个空值的方法,用lateinit不用担心空值的问题。
It is a best practice to use lateinit with fields that hold views in just this way.