What if your Kotlin code could speak Java's language perfectly without extra hassle?
Why Kotlin annotations for Java callers (@JvmStatic, @JvmField)? - Purpose & Use Cases
Imagine you wrote a Kotlin class with some functions and properties, but now you need to use it from Java code. You try to call those Kotlin members from Java, but the syntax is confusing and sometimes you can't access them directly.
Without special annotations, Java callers see Kotlin code differently. Static functions in Kotlin become instance methods in Java, and properties become getter/setter methods. This makes Java code verbose and error-prone, and sometimes you can't access what you want easily.
Using Kotlin annotations like @JvmStatic and @JvmField tells the compiler to generate Java-friendly code. @JvmStatic makes functions appear as static methods in Java, and @JvmField exposes properties as public fields. This makes calling Kotlin code from Java simple and natural.
class Utils { companion object { fun greet() = "Hello" val version = "1.0" } } // Java call: Utils.Companion.greet(); Utils.Companion.getVersion();
class Utils { companion object { @JvmStatic fun greet() = "Hello" @JvmField val version = "1.0" } } // Java call: Utils.greet(); Utils.version;
This lets Kotlin code feel natural and easy to use from Java, improving interoperability and reducing confusion.
When building Android apps, you often mix Kotlin and Java. Using these annotations helps Java parts call Kotlin utilities or constants cleanly without awkward syntax.
Calling Kotlin from Java can be confusing without help.
@JvmStatic and @JvmField make Kotlin members look like normal Java static methods and fields.
This improves code clarity and reduces errors when mixing Kotlin and Java.