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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 @file:JvmMultifileClass works when multiple files are all annotated with @file:JvmMultifileClass and @file:JvmName("ObjectTest"). This works, always.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.