@JvmStatic methods

Similarly to properties, we can apply @JvmStatic to methods defined on companion objects or named objects. Let's examine this by adding a method to our existing companion object:

class Widget {
companion object {
...

fun goo() { }
}
}

From Java, we can then use this method by once again using an instance of the companion object:

// Main.java
public class Main {
public static void main(String[] args) {
Widget.Companion.goo();
}
}

In this example, we must reference the companion object instance because the goo() method is a member of the companion object itself, as seen in the following generated code:

public final class Widget {
...
public static final class Companion {
...

public final void goo() {
}

...
}
}

To move this generated goo() method to the Widget class itself, we can once again apply the @JvmStatic annotation:

class Widget {
companion object {
...

@JvmStatic
fun goo() { }
}
}

Adding the @JvmStatic annotation to the companion object declaration of goo() will indicate to the compiler that it should generate a static method, goo(), on the Widget class itself:

public final class Widget {
...

@JvmStatic
public static final void goo() {

Companion.goo();
}

public static final class Companion {
...
}
}

Once the compiler has generated the true JVM static method, it can be accessed from Java without needing to reference, or know about, the companion object:

// Main.java
public class Main {
public static void main(String[] args) {
Widget.goo();
}
}

By writing your function with @JvmStatic, the code can be used from Java like any other static method in your Java code base. If you're working in a code base with a lot of Java and Kotlin code, this familiar syntax and usage might be a desirable trait.