本文介绍了Kotlin-如何在"lateinit"和"lateinit"之间做出决定和“可为空的变量"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对lateinit和可为空的变量感到困惑,后者用于变量.
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 not added initialisation for c than throws UninitializedPropertyAccessException
if (c == "UserDefinedTarget") {
//do some stuff.
}
//not throws any exception whether d is initialise or not.
if(d == "UserDefinedTarget") {
//do some stuff
}
推荐答案
可为空的类型就是这样,即具有有效状态为null的东西.
A type that is nullable is just that, a thing that has a valid state that is null.
不可为空的延迟初始化var表示其中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活动是使用Lateinit的一个很好的例子.活动必须具有no args构造函数,并且它们的生命周期只能从onCreate()开始.
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().
这篇关于Kotlin-如何在"lateinit"和"lateinit"之间做出决定和“可为空的变量"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!