DEV Community

Cover image for JvmStatic Annotation in Kotlin
Amit Shekhar
Amit Shekhar

Posted on • Originally published at amitshekhar.me

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() {

    }

}
Enter fullscreen mode Exit fullscreen mode

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

AppUtils.install()
Enter fullscreen mode Exit fullscreen mode

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

AppUtils.install(); // compilation error
Enter fullscreen mode Exit fullscreen mode

We get the compilation error.

We will have to call it as below:

AppUtils.INSTANCE.install(); // works
Enter fullscreen mode Exit fullscreen mode

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() {

    }

}
Enter fullscreen mode Exit fullscreen mode

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

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

AppUtils.install();
Enter fullscreen mode Exit fullscreen mode

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:

Top comments (0)