DEV Community 👩‍💻👨‍💻

Cover image for JvmField Annotation in Kotlin
Amit Shekhar
Amit Shekhar

Posted on • Originally published at amitshekhar.me

JvmField 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 JvmField annotation in Kotlin.

This article was originally published at amitshekhar.me.

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 JvmField 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())
Enter fullscreen mode Exit fullscreen mode

We can create the object and get the name in Kotlin as below:

val session = Session("Session", Date())
val name = session.name
Enter fullscreen mode Exit fullscreen mode

It works as expected.

But, when we create the object and get the name from Java as below:

Session session = new Session("Session", new Date());
String name = session.name; // compilation error
Enter fullscreen mode Exit fullscreen mode

It will not compile. From Java, we will have to use the getter method as below:

Session session = new Session("Session", new Date());
String name = session.getName();
Enter fullscreen mode Exit fullscreen mode

Now, it will compile and work as expected.

So, the question is: Can we use it without the getter method as we use in Kotlin?

The answer is yes. By using the JvmField annotation. So, if we want a field to be used as a normal field and not as a getter or setter then we will have to tell the compiler not to generate any getter and setter for the same and expose it as a field by using the @JvmField annotation.

Let's update our data class Session as below:

data class Session(@JvmField val name: String, val date: Date = Date())
Enter fullscreen mode Exit fullscreen mode

Notice that we have used @JvmField over the field name to instruct the Kotlin compiler not to generate any getter and setter for the same and expose it as a field.

Now, if we create the object and get the name from Java as below:

Session session = new Session("Session", new Date());
String name = session.name;
Enter fullscreen mode Exit fullscreen mode

Now, it works perfectly. It will compile as expected as the Kotlin compiler will not generate any getter and setter for the same and expose it as a field.

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

That's it for now.

Thanks

Amit Shekhar

You can connect with me on:

Read all of my high-quality blogs here.

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.