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?

Ryan M
  • 18,333
  • 31
  • 67
  • 74
EmmanuelMess
  • 1,025
  • 2
  • 17
  • 31
  • 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](/questions/40352684) [existing](/questions/40352684) [questions](/questions/43857824) [about](/questions/40352879) [statics](/questions/38381748) [in Kotlin](/questions/46782775)? – gidds May 24 '21 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 – EmmanuelMess May 24 '21 at 21:21
  • Does this answer your question? [What is the equivalent of Java static methods in Kotlin?](https://stackoverflow.com/questions/40352684/what-is-the-equivalent-of-java-static-methods-in-kotlin) – Joffrey May 24 '21 at 22:14
  • Do companion objects create a new underlying object? – EmmanuelMess May 24 '21 at 22:18
  • @EmmanuelMess `companion object`s are `object`s. 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? – Joffrey May 24 '21 at 22:29

1 Answers1

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.

Ryan M
  • 18,333
  • 31
  • 67
  • 74