我对 lateinit 和可为空的变量感到困惑,哪一个用于变量。
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 的类型就是这样,具有为 null 的有效状态的事物。
不可为空的后期初始化变量表示 null 是无效状态,但由于某种原因您不能在构造函数中填充它。
Android Activity 是使用 lateinit 的一个很好的例子。 Activity 必须有一个无参数的构造函数,并且它们的生命周期仅从 onCreate() 开始。
关于android - Kotlin - 如何在 "lateinit"和 "nullable variable"之间做出决定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44796102/