1

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).

vanshg
  • 1,125
  • 2
  • 10
  • 19

1 Answers1

4

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.

ice1000
  • 6,406
  • 4
  • 39
  • 85
  • Perfect, thank you! As a follow up, for my specific use case, if I then wanted to split the methods of this into multiple files (but still accessible to Java via ObjectTest.x for all methods) how would I go about doing that, if at all? I was attempting to use ```@file:JvmMultifileClass @file:JvmName("ObjectTest")``` But that doesn't seem to do the trick for multifile. Is it because the annotation only works for classes and now this is no longer a class? Would there be a way to do what I'm asking in the original question and have a multifile class? – vanshg May 15 '18 at 17:15
  • @vanshg `@file:JvmMultifileClass` works when multiple files are all annotated with `@file:JvmMultifileClass` and `@file:JvmName("ObjectTest")`. This works, always. – ice1000 May 16 '18 at 01:01