Search code examples
kotlinobjectstatic-methods

How to create static functions in Kotlin without creating an object


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?


Solution

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