1

I want to have functions that sit in classes (not polluting the global namespace) but are accessed statically (never creating an object in which they reside). Proposed solution:

object A {
  @JvmStatic
  fun mkdir() {}
}

Is this a good solution or will it inevitably create an object? Which pattern should I use?

5
  • 1
    Top-level functions don't pollute the global namespace — only the namespace of the package the file is in.  And doesn't the object keyword give you a hint about whether this uses an object?  Also, have you checked the many existing questions about statics in Kotlin? Commented May 24, 2021 at 20:59
  • @gidds "Top-level functions don't pollute the global namespace" Fair point, what I meant to say is that you don't know where the function is at a glance, unless you add part of the package to the call. About the existing questions: they just give the standard object pattern, which seems to always create a singleton Commented May 24, 2021 at 21:21
  • Does this answer your question? What is the equivalent of Java static methods in Kotlin? Commented May 24, 2021 at 22:14
  • Do companion objects create a new underlying object? Commented May 24, 2021 at 22:18
  • @EmmanuelMess companion objects are objects. An object declaration in Kotlin is translated into a regular class with a statically initialized unique instance. With @JvmStatic, the method mkdir will be static, but the unique instance will be created nevertheless when the class is initialized. What exactly are you concerned about with the creation of a singleton? Commented May 24, 2021 at 22:29

1 Answer 1

1

Unfortunately, there's currently no way to create a static function on a class in Kotlin that doesn't result in the instantiation of an Object (the companion object). You'll have to write it in Java and call it from Kotlin if you want to do this.

The @JvmStatic annotation creates a static method in the JVM bytecode, but all that does is retrieve the instance of the companion object and call the method on it, which you can verify by decompiling the resulting bytecode.

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

1 Comment

Does Proguard remove the unused instantiation?

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.