In Kotlin there appears to be two method of declaring a variable inside an object that can be null and instantiated after the object is created.

var myObject : Any? = null

or

var lateinit myObject : Any  

I am confused about why the lateinit keyword is needed if we can just make the var nullable and assign it later. What are the pros and cons of each method and in what situation should each one be used?

推荐答案

Here is how I see the difference according to my current knowledge in Kotlin.

第一个:

var myObject1 : Any? = null

这里的myObject1是一个可以为空的属性.这意味着您可以将null分配给它.

Second one:

lateinit var myObject2 : Any

这里myObject2是一个非空属性.这意味着你不能给它分配null.通常,如果属性为非null,则必须在声明时对其进行初始化.但是添加关键字lateinit可以推迟初始化.如果在初始化lateinit属性之前try 访问它,则会出现异常.

In short the main difference is that myObject1 is a nullable and myObject2 is a non-null. The keyword lateinit provide you a convenience mechanism to allow a non-null property to be initialize at a later time rather than initializing it at the declaration.

更多信息请点击this.

Kotlin相关问答推荐

Android Studio中的只读集合不支持操作失败的原因是什么?

在Kotlin中,我是否可以访问已知的WHEN子句值?

捕捉异常是Kotlin协程中的反模式吗?

访问者闭包中的Kotlin序列yield 率

Kotlin扩展函数未调用Hibernate/JPA中的重写函数

如何检测一个值是否是Kotlin中的枚举实例?

同时也是一个字符串的 Kotlin 枚举

如何将消费者放入 Kotlin 的 map 中?

在jetpack compose中将默认方向设置为横向?

测试协程和线程之间的差异,我在kotlin中使用线程时无法得到OOM错误

如何从 kotlin 中的数据类访问 val?

将子元素放在一个列表中

IntentService (kotlin) 的默认构造函数

如何修复 ViewPager2 中的Design assumption violated错误?

Kotlin suspend fun

当被Spring代理类访问时,Kotlin实例变量为null

使用范围的稀疏sparse值列表

参数不匹配;SimpleXML

如何限制kotlin协程的最大并发性

Kotlin 的数据类 == C# 的 struct ?