isInitialized - 此时无法访问 lateinit var 的支持字段
isInitialized - Backing field of lateinit var is not accessible at this point
我正在尝试检查 lateinit
属性 是否已初始化。
在 Kotlin 1.2 中,我们现在有了 isInitialized
方法。当我在声明 lateinit 属性 的 class 中执行此操作时,它会起作用。
但是当我尝试从另一个 class 调用它时,我收到以下警告:
Backing field of 'lateinit var foo: Bar' is not accessible at this point
我的模型class(比方说Person
)是用Java
写的
另外两个 classes(假设 Test1
和 Test2
)是用 Kotlin
编写的
示例:
class Test1 {
lateinit var person: Person
fun method() {
if (::person.isInitialized) {
// This works
}
}
}
-
class Test2 {
lateinit var test1: Test1
fun method() {
if (test1::person.isInitialized) {
// Error
}
}
}
有没有机会让它工作?
我目前的解决方法是在 returns isInitialized
来自 person
属性 的 Test1 中创建一个方法。
fun isPersonInitialized(): Boolean = ::person.isInitialized
//in Test2:
if (test1.isPersonInitialized()) {
// Works
}
根据 docs:
This check is only available for the properties that are lexically accessible, i.e. declared in the same type or in one of the outer types, or at top level in the same file.
这就是为什么您无法在主函数中检查它的原因。
针对 描述的约束的一个非常简单的解决方法如下:
class LateClass {
lateinit var thing: Thing
fun isThingInitialized() = ::thing.isInitialized
}
class Client {
val lateClass = LateClass()
... things happen ...
if (lateClass.isThingInitialized() {
// do stuff with lateClass.thing, safely
}
}
我的 Kotlin 版本 属性。
class LateClass {
lateinit var thing: Thing
val isThingInitialized get() = this::thing.isInitialized
}
我正在尝试检查 lateinit
属性 是否已初始化。
在 Kotlin 1.2 中,我们现在有了 isInitialized
方法。当我在声明 lateinit 属性 的 class 中执行此操作时,它会起作用。
但是当我尝试从另一个 class 调用它时,我收到以下警告:
Backing field of 'lateinit var foo: Bar' is not accessible at this point
我的模型class(比方说Person
)是用Java
写的
另外两个 classes(假设 Test1
和 Test2
)是用 Kotlin
示例:
class Test1 {
lateinit var person: Person
fun method() {
if (::person.isInitialized) {
// This works
}
}
}
-
class Test2 {
lateinit var test1: Test1
fun method() {
if (test1::person.isInitialized) {
// Error
}
}
}
有没有机会让它工作?
我目前的解决方法是在 returns isInitialized
来自 person
属性 的 Test1 中创建一个方法。
fun isPersonInitialized(): Boolean = ::person.isInitialized
//in Test2:
if (test1.isPersonInitialized()) {
// Works
}
根据 docs:
This check is only available for the properties that are lexically accessible, i.e. declared in the same type or in one of the outer types, or at top level in the same file.
这就是为什么您无法在主函数中检查它的原因。
针对
class LateClass {
lateinit var thing: Thing
fun isThingInitialized() = ::thing.isInitialized
}
class Client {
val lateClass = LateClass()
... things happen ...
if (lateClass.isThingInitialized() {
// do stuff with lateClass.thing, safely
}
}
我的 Kotlin 版本 属性。
class LateClass {
lateinit var thing: Thing
val isThingInitialized get() = this::thing.isInitialized
}