Kotlin - 如何在“lateinit"和“lateinit"之间做出决定和“可空变量"? [英] Kotlin - How to decide between "lateinit" and "nullable variable"?

查看:28
本文介绍了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 的类型就是具有为 null 的有效状态的事物.

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

不可为空的后期初始化变量表示 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 的一个很好的例子.活动必须有一个无参数的构造函数,它们的生命周期才真正从 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"之间做出决定和“可空变量"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆