Kotlin: Java can't resolve Kotlin character?

I have Kotlin code as below, SingleKotlin.instance can be called by other Kotlin files

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

However, when I try to call SingleKotlin.instance from java, it shows that it cannot resolve the instance symbol

I don’t understand why, can anyone explain and how can I solve this problem?

+5
source share
5 answers

Just add a @JvmStatic note above the field (as said in this documentation https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-fields )

So your code should look like this:

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

And now you can call it like

 SingleKotlin.instance 
+4
source

In addition to @YuriiKyrylchuk's answer: another option (and the only option if you don't have control over the Kotlin code) is the Java link MyClass.Companion . Example:

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

And in Java:

 MyClass.Companion.getX(); 
+3
source

If your SingleKotlin object has a single private constructor without parameters, you can use object instead:

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

Then in Java you refer to the static INSTANCE field:

 SingleKotlin single = SingleKotlin.INSTANCE; // or SingleKotlin.INSTANCE.getX(); 
+3
source

You need to call the method from Java as follows:
AppUIUtils.Companion.yourMethod()

0
source

In addition to Elijah's answer, you can use the @JvmStatic annotation

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

Then in java

 SingleKotlin.getX(); 
0
source

Source: https://habr.com/ru/post/1263353/


All Articles