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

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

    If you use an unchangable variable, then it is better to initialize with by lazy { ... } or val. In this case you can be sure that it will always be initialized when needed and at most 1 time.

    If you want a non-null variable, that can change it's value, use lateinit var. In Android development you can later initialize it in such events like onCreate, onResume. Be aware, that if you call REST request and access this variable, it may lead to an exception UninitializedPropertyAccessException: lateinit property yourVariable has not been initialized, because the request can execute faster than that variable could initialize.

提交回复
热议问题