Do you really need JvmStatic annotation?

Taku Semba
2 min readMar 1, 2019

--

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 acompanion object scope like this below, you can access it like Greeter.hello() from Java code.

Greeter.kt

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
@Lkotlin/jvm/JvmStatic;()
L0
GETSTATIC com/takusemba/jvmstatic/Greeter.Companion : Lcom/takusemba/jvmstatic/Greeter$Companion;
INVOKEVIRTUAL com/takusemba/jvmstatic/Greeter$Companion.hello ()V
RETURN
L1
MAXSTACK = 1
MAXLOCALS = 0

Let’s see decompiled java code to make it easier to understand.

with JvmStatic
without JvmStatic

Basically, @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.

So, JvmStatic

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

--

--