DEV Community

Cover image for JvmStatic Annotation in Kotlin
Amit Shekhar
Amit Shekhar

Posted on • Edited on • Originally published at outcomeschool.com

JvmStatic Annotation in Kotlin

Hi, I am Amit Shekhar, Co-Founder @ Outcome School • IIT 2010-14 • I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

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

This article was originally published at Outcome School.

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

Co-Founder @ Outcome School

You can connect with me on:

Read all of our blogs here.

Top comments (0)