JvmStatic, JvmOverloads, and JvmField in Kotlin
In this article, we’ll look at how to utilize Kotlin code in our current Java code using @JvmStatic, @JvmOverloads, and @JvmField in Kotlin. You may invoke Kotlin code from Java code and vice versa. This blog will concentrate on invoking Kotlin code from Java code.
As you can see in the preceding code, calling the Kotlin code from the Java code is fairly straightforward, but there are times when it is not. In those instances, we utilize @JvmStatic, @JvmOverloads, and @JvmField in Kotlin to make it simple for someone calling the Kotlin code from Java.
Package-level functions are represented as static methods in Kotlin. You can also use the @JvmStatic annotation in Kotlin to create static methods for functions specified in a companion object or named object. As an example:
Let’s call Kotlin now:
You’ll need to make a call like this from Java.
How can we make it function if we don’t use the INSTANCE?
JvmStatic is the answer.
If you do not supply a date in the argument, the current date will be used by default in the above code. So, if we call from Kotlin, the following code will execute without error:
However, if we call the same function from Java, we must supply all of the arguments, or we would receive the following error:
We’ve passed both arguments. So, what’s the point of using the default value if we have to pass both values?
So, we can use the @JvmOverloads annotation to utilize the default value. Following the use of the annotation, the Kotlin code will be:
data class GeeksforGeeks @JvmOverloads constructor( val articleName: String, val date: Date = Date())
Let’s use the Event class from the previous section of the article as an example.
data class GeeksforGeeks ( val articleName: String, val date: Date = Date())
So, if you want a certain field to be utilized as a regular field rather than a getter or setter, you must instruct the compiler not to produce any getter or setter for it, which you can accomplish by using the @JvmField annotation. So, after applying the @JvmField annotation, the Kotlin code will be:
data class Article (@JvmField val geeksforgeeks: String, val date: Date = Date())
Now, in Java, you can access the class’s fields in the same manner as you can in Kotlin: