Search code examples
javakotlinsingle-instance

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?


Solution

  • 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