Member-only story

@JvmField Annotation in Kotlin

Simplifying Interoperability with Java — Part 2

Android Dev Nexus
3 min readOct 12, 2024

Here’s a special treat for our non-Medium members: we’re offering free access to this blog! Just follow this link — because your curiosity and passion for coding should never be limited! 😉😉

👻 Hello dear Kotlin witches and warlocks! 🎃

As the moon rises and the shadows grow longer, it’s time to brew up another magical potion from the depths of Kotlin’s spellbook. Today, we summon the powers of @JvmField! 🧙‍♀️ This little-known incantation can turn your Kotlin properties into fields that even Java can access without chanting "getter" or "setter" spells.

Ready to conjure up some field magic? Let’s begin… 👻

Example with Data Class and @JvmField

Let’s summon a Kotlin data class that we want to expose to Java. Normally, Kotlin automatically generates getter and setter methods for each property.

data class User(
var name: String = "Agatha",
val age: Int = 550
)

When this Kotlin code is compiled to Java bytecode, it generates:

public class User {
private String name = "Agatha"; // Backing field for `name`
private final int age = 550; // Backing field for `age`…

--

--

Android Dev Nexus
Android Dev Nexus

Written by Android Dev Nexus

Your friendly neighborhood developers working at PayPal, turning Android fundamentals into concepts you’ll actually understand.

Responses (2)