user3239558
user3239558

Reputation: 1827

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?

Upvotes: 7

Views: 5724

Answers (5)

Yurii Kyrylchuk
Yurii Kyrylchuk

Reputation: 819

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

Upvotes: 7

polis
polis

Reputation: 1033

In additional to Ilya answer you can use @JvmStatic annotation

object SingleKotlin {
    // some members of SingleKotlin

    @JvmStatic val x = 42
}

Then in Java

SingleKotlin.getX();

Upvotes: 0

user961376
user961376

Reputation:

You need to call the method from Java like this:
AppUIUtils.Companion.yourMethod()

Upvotes: 0

Ilya
Ilya

Reputation: 23164

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();

Upvotes: 3

hotkey
hotkey

Reputation: 148179

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();

Upvotes: 3

Related Questions