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不能与基元类型一起使用.为什么会这样?

推荐答案

对于(不可为null的)对象类型,Kotlin使用null值来标记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).

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

Kotlin相关问答推荐

Kotlin:有限的并行性并不是限制并行性

Scala性状线性化等价于Kotlin

Kotlin stlib中是否有用于将列表<;对<;A,B&>;转换为对<;列表<;A&>,列表<;B&>;的函数

禁用 Gradle执行消息

通过快捷键手动砍掉功能参数等

Kotlin .如何用从 1 到 90 的 5 个唯一数字填充列表中的每一行?

Kotlin:我可以将函数分配给 main 的伴随对象中的变量吗?

如何使用 Mockk 模拟返回值类的 Kotlin 函数类型?

当 func 重载时,kotlin 如何确定调用哪个 func?

Kotlin 中的as Long和.toLong()有什么区别?

为什么没有remember 的 mutableStateOf 有时会起作用?

在 kotlin 中模拟伴随对象函数

Kotlin RxJava 可空的错误

致命错误 LifecycleOwners 必须在 registerForActivityResult 开始之前调用 register

API 'variant.getJavaCompile()' 已过时

Kotlin 类的调用方法

Kotlin - 覆盖方法中的 IllegalArgumentException

面临一些未知问题一些后端jvm内部错误

在 suspendCoroutine 块中调用挂起函数的适当方法是什么?

访问Kotlin中的属性委托