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() {
}
}
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
Co-Founder @ Outcome School
You can connect with me on:
Top comments (0)