Kotlin - Property initialization using “by lazy” vs. “lateinit”

后端 未结 8 1089
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 14:50

In Kotlin if you don\'t want to initialize a class property inside the constructor or in the top of the class body, you have basically these two options (from the language r

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 15:41

    Very Short and concise Answer

    lateinit: It initialize non-null properties lately

    Unlike lazy initialization, lateinit allows the compiler to recognize that the value of the non-null property is not stored in the constructor stage to compile normally.

    lazy Initialization

    by lazy may be very useful when implementing read-only(val) properties that perform lazy-initialization in Kotlin.

    by lazy { ... } performs its initializer where the defined property is first used, not its declaration.

提交回复
热议问题