Search code examples
kotlinkotlin-interop

Is there a way to hide the INSTANCE variable on a Kotlin singleton object


If I have code like this

object ObjectTest {
    @JvmStatic
    fun init() {

    }
}

is it possible to hide the ObjectTest.INSTANCE variable that Kotlin automatically generates? I don't want the object to be accessible via an instance and nor will it have any instance methods, so the INSTANCE variable is just polluting autocomplete and could be confusing to potential users (This code is for a library that will be consumed by others).


Solution

  • Yes, you can do it, by converting an object into a plain file.

    @file:JvmName("ObjectTest")
    // maybe a package statement here
    fun init() {
      // here `init` is public static final void
    }
    

    And there's no INSTANCE object. In Kotlin this is a top-level function, but in Java it's a class named ObjectTest with a private constructor and it has a public static final void method called init.