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

后端 未结 8 1111
没有蜡笔的小新
没有蜡笔的小新 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:40

    Additionnally to hotkey's good answer, here is how I choose among the two in practice:

    lateinit is for external initialisation: when you need external stuff to initialise your value by calling a method.

    e.g. by calling:

    private lateinit var value: MyClass
    
    fun init(externalProperties: Any) {
       value = somethingThatDependsOn(externalProperties)
    }
    

    While lazy is when it only uses dependencies internal to your object.

提交回复
热议问题