为什么 Kotlin 不允许对原始类型使用 lateinit? [英] Why doesn't Kotlin allow to use lateinit with primitive types?

查看:44
本文介绍了为什么 Kotlin 不允许对原始类型使用 lateinit?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Kotlin 语言中,默认情况下,我们必须在引入每个变量时对其进行初始化.为了避免这种情况,可以使用 lateinit 关键字.在初始化之前引用 lateinit 变量会导致运行时异常.

In the Kotlin language we, by default, have to initialize each variable when it is introduced. To avoid this, the lateinit keyword can be used. Referring to a lateinit variable before it has been initialized results in a runtime exception.

lateinit 不能与原始类型一起使用.为什么会这样?

lateinit can not, however, be used with the primitive types. Why is it so?

推荐答案

对于(不可为空的)对象类型,Kotlin 使用 null 值来标记一个 lateinit属性尚未初始化并在访问该属性时抛出相应的异常.

For (non-nullable) object types, Kotlin uses the null value to mark that a lateinit property has not been initialized and to throw the appropriate exception when the property is accessed.

对于原始类型,没有这样的值,因此无法将属性标记为未初始化并提供 lateinit 需要提供的诊断.(我们可以尝试使用某种单独的标记,但是当通过反射初始化字段时,该标记不会更新,这是 lateinit 的一个主要用例).

For primitive types, there is no such value, so there is no way to mark a property as non-initialized and to provide the diagnostics that lateinit needs to provide. (We could try to use a separate marker of some kind, but that marker would not be updated when initializing the field through reflection, which is a major use case of lateinit).

因此,lateinit 仅支持对象类型的属性.

Therefore, lateinit is supported for properties of object types only.

这篇关于为什么 Kotlin 不允许对原始类型使用 lateinit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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