Android Kotlin / The lateinit keyword

 通常,一個變量在被用到之前不需要初始化,而佔用內存。

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.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章