Kotlin: Java can't resolve Kotlin Symbol?
Asked Answered
S

5

7

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?

Stanford answered 25/1, 2017 at 19:47 Comment(0)
P
7

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
Pus answered 25/1, 2017 at 19:51 Comment(3)
Thanks for Yurii Kyrylchuk answer, after add @JvmField, in java code, I have to use "SingleKotlin.getInstance()"Stanford
@JvmField cannot be applied to a delegated property, however @JvmStatic can. It would make the getter of that property exposed in the static scope of the containing class, so you have to call that getter as SingleKotlin.getInstance()Anthropomorphosis
Sorry, I made a mistake, after added @JvmStatic, I use SingleKotlin.getInstance()"Stanford
B
3

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();
Bonnet answered 25/1, 2017 at 20:35 Comment(0)
A
3

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();
Anthropomorphosis answered 26/1, 2017 at 2:2 Comment(0)
N
0

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

Namnama answered 10/3, 2017 at 14:33 Comment(0)
C
0

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();
Caret answered 24/10, 2017 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.