Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 462
user3239558 Avatar asked Jan 25 '17 19:01

user3239558


3 Answers

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
like image 108
Yurii Kyrylchuk Avatar answered Nov 09 '22 00:11

Yurii Kyrylchuk


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();
like image 3
hotkey Avatar answered Nov 08 '22 22:11

hotkey


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();
like image 3
Ilya Avatar answered Nov 09 '22 00:11

Ilya