Do you really need JvmStatic annotation?
Kotlin has a JvmStatic annotation, and in this article, I will go through about what JvmStatic annotation does and the necessity of it.
If you add
@JvmStatic to functions, in a
companion object scope like this below, you can access it like
Greeter.hello() from Java code.
What JvmStatic annotation does
To know what JvmStatic annotation does, let’s compare java bytecodes between the one without JvmStatic and the one with JvmStatic.
If you add a JvmStatic annotation, only this bytecode is added and everything else is the same.
// access flags 0x19
public final static hello()V
GETSTATIC com/takusemba/jvmstatic/Greeter.Companion : Lcom/takusemba/jvmstatic/Greeter$Companion;
INVOKEVIRTUAL com/takusemba/jvmstatic/Greeter$Companion.hello ()V
MAXSTACK = 1
MAXLOCALS = 0
Let’s see decompiled java code to make it easier to understand.
@JvmStatic in a
companion object does not make the function static, it just creates a helper method to access the Companion object and does nothing more than that.
・makes it easier to access from Java code 😄
・increases method count 😅
In my opinion, if your project is all written in Kotlin and not used from Java code, you do not need JvmStatic Annotation.