Home > Software design >  How to refer to a Kotlin delegating singleton object from Java?
How to refer to a Kotlin delegating singleton object from Java?

Time:10-17

I have a Kotlin object that delegates it's implementation, in my case to MutableSet<String> like so:

object MySet : MutableSet<String> by TreeSet<String>() {

    init {...}

}

In Java I'd like to say something like MySet.contains. How can I do that?

CodePudding user response:

object declares a singleton. Unlike Kotlin, you cannot use a type name to refer to its instance in Java. Therefore, the Kotlin compiler translates the singleton instance to a field called INSTANCE instead, so you can do:

MySet.INSTANCE.contains(foo);

in Java.

While you can probably find INSTANCE by chance, just by using the auto-complete in IntelliJ, the only place where I could find this officially documented is in the Calling Kotlin from Java page at the bottom of this section, which talks about calling static methods.

object Obj {
    @JvmStatic fun callStatic() {}
    fun callNonStatic() {}
}

In Java:

Obj.callStatic(); // works fine
Obj.callNonStatic(); // error
Obj.INSTANCE.callNonStatic(); // works, a call through the singleton instance
Obj.INSTANCE.callStatic(); // works too
  • Related