JvmStatic Annotation in Kotlin

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
JvmStatic Annotation in Kotlin

I am Amit Shekhar, Co-Founder @ Outcome School, 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.

Join Outcome School and get high paying tech job: Outcome School

Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out Android Interview Questions and Answers.

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

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. So, the compiler will generate an additional static method for us.

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.

Learn about JvmOverloads: JvmOverloads Annotation in Kotlin

Learn about JvmField: JvmField Annotation in Kotlin

Watch the video format: JvmStatic Annotation in Kotlin

Prepare yourself for Android Interview: Android Interview Questions

That's it for now.

Thanks

Amit Shekhar
Co-Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.