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

后端 未结 4 629
感情败类
感情败类 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 00:59

    It depends. Nullable variable means that variable can hold value or null. lateinit means that variable must be initialised later. It should be initialized before accessing it. If you attempt accessing uninitialized lateinit variable UninitializedPropertyAccessException will be thrown.

    It's always better to avoid using nulls in your app. Nulls are evil. So if you can initialize variable in onCreate then it's better to use lateinit. Also if you use dependency injection in your app and fields should be injected it's also a valid case to use lateinit instead of handling nulls.

    If for some reason you can't initialize variable, initializing code can result to null, or null can be assigned to this variable later than you should use nullable variable. Generally speaking if null is a valid value for the variable.

提交回复
热议问题