I have a Kotlin Code just like the below, SingleKotlin.instance
can be called by the 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 can't resolve symbol '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)
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. Example:
class MyClass {
companion object {
val x: Int = 0
}
}
And in Java:
MyClass.Companion.getX();
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 reference it through the INSTANCE
static field:
SingleKotlin single = SingleKotlin.INSTANCE;
// or
SingleKotlin.INSTANCE.getX();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With