What is JvmStatic annotation in Kotlin and why we use it

Introduction :

JvmStatic annotation or @JvmStatic is an important annotation of Kotlin. In this post, I will show you where JvmStatic is used and its use cases.

Companion object in Kotlin :

Companion object is similar to static properties and methods of Java. Using a companion object, we can make one function or property of a class available on class level. Without creating an object, we can access that property or function.

The syntax of companion object is as like below :

class <ClassName> {
    companion object <CompanionObjectName>{
        //function and other properties

The companion object is a singleton and its members can be accessed via the classname without creating an object for that class. One class can have only one companion object. If we don’t give any name to a companion object, it takes the default name Companion.

JvmStatic :

@JvmStatic annotation can be used with properties or functions. It makes that function or property static for Java code. i.e. we can access these values as static members from another Java file. For example :

class MyClass {
    companion object {
        @JvmStatic fun functionOne() {}
        fun functionSecond() {}

Now, from a Java file, we can call functionOne as a static method, MyClass.functionOne(). But we can’t call functionSecond as static method.

Same for named objects and companion objects defined in an interface.

Similar tutorials :