isInitialized-此时无法访问lateinit var的后备字段 [英] isInitialized - Backing field of lateinit var is not accessible at this point
问题描述
我正在尝试检查lateinit
属性是否已初始化.
在Kotlin 1.2中,我们现在有了isInitialized
方法.当我在声明lateinit属性的类中执行此操作时,它将起作用.
但是,当我尝试从另一个类调用它时,会收到以下警告:
I'm trying to check if a lateinit
property has been initialized.
In Kotlin 1.2 we now have the isInitialized
method for that. It works when I do that in the class where the lateinit property is declared.
But when I try to call this from another class I get the following warning:
"lateinit var foo:Bar"的后备字段目前无法访问
Backing field of 'lateinit var foo: Bar' is not accessible at this point
我的模型类(比如说Person
)是用Java编写的.
用Kotlin编写了另外两个类(假设Test1
和Test2
)
My model class (let's say Person
) is written in Java
Two other classes (let's say Test1
and Test2
) are written in 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
}
}
}
有没有机会使它正常工作?
Any chance to get this working?
我当前的解决方法是在Test1中创建一个方法,该方法从person
属性返回isInitialized
.
My current workaround is to make a method in Test1 which returns isInitialized
from the person
property.
fun isPersonInitialized(): Boolean = ::person.isInitialized
//in Test2:
if (test1.isPersonInitialized()) {
// Works
}