JvmStatic Annotation in Kotlin

JvmStatic Annotation in Kotlin

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

In this blog, we are going to learn about the JvmStatic annotation in Kotlin.

This article was originally published at amitshekhar.me.

The best thing about Kotlin is that it is designed with Java interoperability in mind. It means that the existing Java code can be called from Kotlin, and also the Kotlin code can be called from Java. Both ways are supported.

Today, we will focus on calling the Kotlin code from Java as we want to learn about the JvmStatic annotation.

The best way to learn this is by taking an example.

Assume that we have a named object AppUtils in Kotlin as below:

object AppUtils {

    fun install() {

    }

}

We can call the install() method in Kotlin as below:

AppUtils.install()

But, when we call install() method from Java as below:

AppUtils.install(); // compilation error

We get the compilation error.

We will have to call it as below:

AppUtils.INSTANCE.install(); // works

This works as expected.

So, the question is: Can we make it work without using that INSTANCE?

The answer is yes. By using the JvmStatic annotation, we can make it work without using that INSTANCE.

For that, we need to update our named object AppUtils in Kotlin as below:

object AppUtils {

    @JvmStatic
    fun install() {

    }

}

Here, we have added @JvmStatic annotation on the method.

Now, we can call install() method from Java as below:

AppUtils.install();

And, it works perfectly.

This is how we can use the JvmStatic annotation in Kotlin.

That's it for now.

Thanks

Amit Shekhar

You can connect with me on: