简体   繁体   English

Kotlin:Java无法解决Kotlin Symbol?

[英]Kotlin: Java can't resolve Kotlin Symbol?

I have a Kotlin Code just like the below, SingleKotlin.instance can be called by the other Kotlin files 我有一个Kotlin代码,如下所示, SingleKotlin.instance可以被其他Kotlin文件调用

class SingleKotlin private constructor(){
    companion object {
        val instance by lazy {
            SingleKotlin()
        }
    }

}

However, when I try to call SingleKotlin.instance from java, it shows can't resolve symbol 'instance' 但是,当我尝试从java调用SingleKotlin.instance时,它显示无法解析符号'instance'

I don't understand why, anybody can explian and how can I solve this problem? 我不明白为什么,任何人都可以探索,我该如何解决这个问题?

Just add @JvmStatic annotation above field (as said in this documentation https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields ) 只需在字段上方添加@JvmStatic注释(如本文档中所述https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields

So, your code should be like this: 所以,你的代码应该是这样的:

class SingleKotlin private constructor(){
    companion object {
        @JvmStatic
        val instance by lazy {
            SingleKotlin()
        }
    }
}

And now you can call it like 现在你可以这样称呼它

SingleKotlin.instance

In addition to @YuriiKyrylchuk 's answer: another option (and the only option if you don't have control over the Kotlin code) is to refer to MyClass.Companion from Java. 除了@YuriiKyrylchuk的回答:另一个选项(如果你无法控制Kotlin代码,唯一的选择)是从Java引用MyClass.Companion Example: 例:

class MyClass {
    companion object {
        val x: Int = 0
    }
}

And in Java: 在Java中:

MyClass.Companion.getX();

If your SingleKotlin object has a single private constructor without parameters, you can use object instead: 如果您的SingleKotlin对象有一个没有参数的私有构造函数,则可以使用object

object SingleKotlin {
    // some members of SingleKotlin
    val x = 42
}

Then in Java you reference it through the INSTANCE static field: 然后在Java中通过INSTANCE静态字段引用它:

SingleKotlin single = SingleKotlin.INSTANCE;
// or
SingleKotlin.INSTANCE.getX();

您需要像这样从Java调用该方法:
AppUIUtils.Companion.yourMethod()

In additional to Ilya answer you can use @JvmStatic annotation 除了Ilya答案,你可以使用@JvmStatic注释

object SingleKotlin {
    // some members of SingleKotlin

    @JvmStatic val x = 42
}

Then in Java 然后在Java中

SingleKotlin.getX();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM