Why and when to use @JvmStatic with companion objects?
Solution 1:
The behavior of the @JvmStatic
annotation is explained in detail in the documentation. When reading the documentation, you should assume that it gives you all the important information, and behavior differences that are not mentioned in the documentation do not exist.
In this case, the documentation says:
If you use this annotation, the compiler will generate both a static method in the enclosing class of the object and an instance method in the object itself.
In other words, the effect of the annotation is that it tells the compiler to generate an additional method.
Does the documentation mention that there is any difference in behavior or memory allocation? It does not. Therefore, it's safe to assume that there is none.
Is there a preference on which one to use? Normally, an API is declared in one place and used from multiple places. If you're calling a method from Java, then you should declare it as @JvmStatic
, because adding the @JvmStatic
annotation in one place will allow you to leave out multiple .Companion
references in multiple places.
Do both create a pseudo static singleton object, like Java static does? This question does not make sense, because Java static does not create a "pseudo static singleton object". If you declare a static method in a Java class, and then call this method, no objects will be created.
Solution 2:
A companion object
is an instance of a real class
called Companion
. So, when you call the Kotlin code from Java, an object of the Companion
class is first instantiated behind the scenes. To understand this, let's consider a simple example.
Behind the scenes without @JvmStatic
Kotlin code
class Plant {
companion object {
fun waterAll() { }
}
}
Decompiled Java code
public final class Plant {
public static final Plant.Companion Companion = new Plant.Companion();
public static final class Companion {
public final void waterAll() { }
private Companion() { }
}
}
As you can see in the simplified decompiled Java code above, a class named Companion
is generated to represent the companion object
. The class Plant
holds the singleton instance new Plant.Companion()
of the class Plant.Companion
. The instance is also named as Companion
. This is the reason you need to call the functions/properties of the companion object
in Java using the Plant.Companion
:
Plant.Companion.waterAll();
Behind the scenes with @JvmStatic
Kotlin code
class Plant {
companion object {
@JvmStatic
fun waterAll() { }
}
}
Decompiled Java code
public final class Plant {
public static final Plant.Companion Companion = new Plant.Companion();
@JvmStatic
public static final void waterAll() { Companion.waterAll();}
public static final class Companion {
@JvmStatic
public final void waterAll() { }
private Companion() { }
}
}
When you annotate a function of a companion object
with @JvmStatic
in Kotlin, a pure static
function waterAll()
is generated in addition to the non static function waterAll()
. So, now you are able to call the function without the Companion
name which is more idiomatic to Java:
Plant.waterAll();
Singleton
The singleton pattern is generated in both cases. As you can see, in both cases, the Companion
instance holds the singleton object new Plant.Companion()
and the constructor is made private
to prevent multiple instances.
The Java static
keyword does not create the singletons. You will get the singleton feature only if you create a companion object
in Kotlin and then use it from Java. To get singleton from Java, you'll need to write the singleton pattern, the code for which looks like the decompiled Java code shown above.
Performance
There is no performance gain or loss in terms of memory allocation. The reason is that, as you can see in the code above, the extra static
function that is generated delegates its work to the non static function Companion.waterAll()
. This means, creation of the Companion
instance is required in both the cases, with @JvmStatic
as well as without @JvmStatic
.
The behaviour of both the setups is the same apart from the extra method that is generated. In Android, if you worry about the method count, you may need to keep an eye on this because an extra copy is created for each annotated function.
When to use @JvmStatic
When you know that your Kotlin code won't be used in Java, you don't have to worry about adding the @JvmStatic
annotation. This keeps your code cleaner. However, if your Kotlin code is called from Java, it makes sense to add the annotation. This will prevent your Java code from polluting with the name Companion
everywhere.
It's not like an additional keyword on either side. If you add @JvmStatic
in one place, you can prevent writing the extra Companion
word in thousands of places, wherever you call that function. This is especially useful for library creators, if they add @JvmStatic
in their Kotlin library, the users of that library won't have to use the Companion
word in their Java code.
That's it! Hopefully that helps get the clearer picture of the @JvmStatic
.
Solution 3:
You place the function in the "companion object".
So the java code like this:
class DemoClass {
public static int myMethod() { return 1; }
}
will become
class DemoClass {
companion object {
fun myMethod() : Int = 1
}
}
You can then use it from inside Kotlin code as
DemoClass.myMethod();
But from within Java code, you would need to call it as
DemoClass.Companion.myMethod();
(Which also works from within Kotlin.)
If you don't like having to specify the Companion
bit you can either add a @JvmStatic
annotation or name your companion class.
From the docs:
Companion Objects
An object declaration inside a class can be marked with the companion keyword:
class MyClass { companion object Factory { fun create(): MyClass = MyClass() } }
Members of the companion object can be called by using simply the class name as the qualifier:
val instance = MyClass.create()
...
However, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the
@JvmStatic
annotation. See the Java interoperability section for more details.
Adding the @JvmStatic
annotation looks like this
class DemoClass {
companion object {
@JvmStatic
fun myMethod() : Int = 1;
}
}
and then a will exist as a real Java static function, accessible from
both Java and kotlin as DemoClass.myMethod()
.
If it is just disliked by the Companion
name, then you can also
provide an explicit name for the companion object looks like this:
class DemoClass {
companion object Blah {
fun myMethod() : Int = 1;
}
}
which will let you call it from Kotlin in the same way, but
from java like DemoClass.Blah.myMethod()
(which will also work in Kotlin).
Solution 4:
In Kotlin, the companion
object can be us used to imitate static behaviour, calls look like static calls in Java, the “Companion“
isn’t part of if. If used in Java though, the companion
object has to be named, unless @JvmStatic
is applied. It’d look less idiomatic otherwise.
TestKotlin.getSomeString() //this should be preferred whenever possible
Stated in the docs:
Companion Objects
An object declaration inside a class can be marked with the companion keyword:
class MyClass { companion object Factory { fun create(): MyClass = MyClass() } }
Members of the companion object can be called by using simply the class name as the qualifier:
val instance = MyClass.create()
...
However, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the
@JvmStatic
annotation. See the Java interoperability section for more details.
Note that it will generate an additional method as stated here:
If you use this annotation, the compiler will generate both a static method in the enclosing class of the object and an instance method in the object itself.
Let's see an example:
The following class
class Outer {
companion object {
fun callMe() = ""
}
}
looks like this on bytecode level, here represented as Java code:
@Metadata(...)
public final class Outer {
public static final Outer.Companion Companion = new Outer.Companion((DefaultConstructorMarker)null);
@Metadata(...)
public static final class Companion {
@NotNull
public final String callMe() {
return "";
}
private Companion() {
}
// $FF: synthetic method
public Companion(DefaultConstructorMarker $constructor_marker) {
this();
}
}
}
If @JvmStatic
is being applied to callMe
method though, the bytecode changes to the following:
@Metadata(...)
public final class Outer {
public static final Outer.Companion Companion = new Outer.Companion((DefaultConstructorMarker)null);
@JvmStatic
@NotNull
public static final String callMe() {
return Companion.callMe();
}
@Metadata(...)
public static final class Companion {
@JvmStatic
@NotNull
public final String callMe() {
return "";
}
private Companion() {
}
// $FF: synthetic method
public Companion(DefaultConstructorMarker $constructor_marker) {
this();
}
}
}
You can see, correctly documented, the static callMe
function, as part of Outer
is generated:
@JvmStatic
@NotNull
public static final String callMe() {
return Companion.callMe();
}