Companion Object Vs @JvmStatic in Kotlin
Hi guys,
Now, we are going to see the difference between the companion object and @JvmStatic in kotlin.
What is a companion Object in Kotlin?
Kotlin language does not have static keyword like java.
So, Its provide companion object {} block instead of static keyword, We can also used @JvmStatic to denote the static variable or methods.
companion object is an instance of the Campanion class, So, When we 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.
Kotlin code (Without @JvmStatic)
class Car {
companion object {
fun getSeatSize() { }
}
}
Decompiled Java code
public final class Car {
public static final Car.Companion Companion = new Car.Companion();
public static final class Companion {
public final void getSeatSize() { }
private Companion() { }
}
}
Java using the Car.Companion:
Car.Companion.getSeatSize();
Kotlin code (With @JvmStatic)
class Car {
companion object {
@JvmStatic
fun getSeatSize() { }
}
}
Decompiled Java code
public final class Car {
public static final Car.Companion Companion = new Car.Companion();
@JvmStatic
public static final void getSeatSize() { Companion.getSeatSize();}
public static final class Companion {
@JvmStatic
public final void getSeatSize() { }
private Companion() { }
}
}
When you annotate a function of a companion object with @JvmStatic in Kotlin, a pure static function getSeatSize() is generated in addition to the non-static function getSeatSize(). So, now you are able to call the function without the Companion name which is more idiomatic to Java:
Car.getSeatSize();
Comments
Post a Comment