为什么Kotlin不允许对原始类型使用lateinit? [英] Why doesn't Kotlin allow to use lateinit with primitive types?
问题描述
默认情况下,使用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 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屋!