isInitialized-此时无法访问lateinit var的后备字段 [英] isInitialized - Backing field of lateinit var is not accessible at this point

查看:408
本文介绍了isInitialized-此时无法访问lateinit var的后备字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查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编写了另外两个类(假设Test1Test2)

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
}

推荐答案

根据

此检查仅适用于可按词法访问的属性,即以相同类型或外部类型之一或同一文件的顶级声明的属性.

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.

这就是为什么您无法在主要功能中进行检查的原因.

Which is why you cannot check that in the main function.

这篇关于isInitialized-此时无法访问lateinit var的后备字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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