JvmOverloads Annotation in Kotlin

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
JvmOverloads 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 JvmOverloads 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 JvmOverloads annotation.

The best way to learn this is by taking an example.

Assume that we have a data class Session in Kotlin as below:

data class Session(val name: String, val date: Date = Date())

We can create the objects in Kotlin as below:

val sessionOne = Session("Session One", Date())
val sessionTwo = Session("Session Two")

Both the lines of the code will compile as expected as for the 2nd object, it will take the default value of the Date.

But, when we create the objects from Java as below:

Session sessionOne = new Session("Session One", new Date());
Session sessionTwo = new Session("Session Two"); // compilation error

The first line will compile, but the second line will not as we have not passed Data as a parameter. It will give us the following error:

Session(java.lang.String, java.util.Date)' in 'com.example.Session' cannot be applied to '(java.lang.String)

As we know that Java does not support default parameters. It supports overloading.

And, Kotlin supports default parameters.

So, we will have to use @JvmOverloads. It instructs the Kotlin compiler to generate overloads for the function that substitute default parameter values.

Let's update our data class Session as below:

data class Session @JvmOverloads constructor(val name: String, val date: Date = Date())

Notice that we have used @JvmOverloads to instruct the Kotlin compiler to generate overloads for the function.

Now, if we create the objects from Java as below:

Session sessionOne = new Session("Session One", new Date());
Session sessionTwo = new Session("Session Two");

And, it works perfectly. Both the lines of the code will compile as expected as the Kotlin compiler has generated the overloads for the function.

This is how we can use the JvmOverloads annotation in Kotlin.

Learn about JvmStatic: JvmStatic Annotation in Kotlin

Learn about JvmField: JvmField Annotation in Kotlin

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.