Kotlin - How to decide between “lateinit” and “nullable variable”?

后端 未结 4 648
感情败类
感情败类 2020-12-14 00:16

I am confuse for lateinit and nullable variable, which one to use for variable.

lateinit var c: String
var d: String? = null
c = \"UserDefinedTarget\"

// if         


        
4条回答
  •  暖寄归人
    2020-12-14 01:01

    A type that is nullable is just that, a thing that has a valid state that is null.

    A non-nullable late init var represents something where null is an invalid state, but for some reason you can't populate it in the constructor.

    Android Activities are a good example of a use of lateinit. Activities must have a no args constructor and their lifecycle only really starts with onCreate().

提交回复
热议问题