CodeGym /Courses /Kotlin SELF /Minimal “Java-friendly” Kotlin API — @file:JvmName and @J...

Minimal “Java-friendly” Kotlin API — @file:JvmName and @JvmField

Kotlin SELF
Level 29, Lesson 4
Available

1. How Java sees Kotlin on the JVM

Today it makes sense to flip the arrow: not “Kotlin calls Java”, but “Java calls Kotlin”. We won’t write Java code as a separate practice, but we’ll figure out how Java will see Kotlin code, and we’ll learn to use two small annotations to make a Kotlin API significantly more convenient for a Java consumer.

Why think about the Java representation at all

Imagine you wrote clean Kotlin code: file-level functions, constants, report formatting. And then a colleague (or you yourself six months later) comes and says: “Can I call this from Java?”. And that’s where a small drama begins: Java doesn’t know about many Kotlin conveniences and sees your code through the JVM lens. That’s why it’s important to understand what names and shapes you get in bytecode, and where you can slightly “sweeten” interop.

In our console program (let it be a mini expense tracker) there are already many utility functions: command parsing, string formatting, report preparation. This is a great candidate for a “small API” that Java code could theoretically use too (for example, another module in your company that hasn’t made it to Kotlin yet — and that’s fine).

Why Java sees a weird SomethingKt

Up to this point we’ve been calmly writing functions “just in a file”:


fun formatMoney(amount: Int): String = "$amount ₣ "

From Kotlin’s point of view, that’s natural: a file is a normal place for utility functions. But on the JVM things are arranged so that functions must “live” inside some class. So the compiler creates a technical wrapper class for you: a file facade (often also called a “file class”).

If your file is named ReportUtils.kt, then Java will typically see something like ReportUtilsKt and static methods inside it. That is, a Java call (roughly) would look like ReportUtilsKt.formatMoney(10).

This is not “bad” and not an “error”. It’s simply the JVM reality: it needs a place to put static methods, and it puts them into a class whose name you might not even have planned to “export for public use”.

2. A human name for the file class: @file:JvmName

When you’re building a library, a utilities module, or simply code that someone will use from the outside, it suddenly becomes important what the name looks like in Java. Naming an API entry point ReportUtilsKt is tolerable, but it slightly “smells like the compiler”. Kotlin lets you fix this with a single annotation: @file:JvmName("...").

The key idea: we control what the JVM file class will be called to the outside world. At the same time, Kotlin code inside the project usually doesn’t suffer at all: in Kotlin you still call functions by their usual names.

It’s also important where to write file annotations. By Kotlin formatting conventions, file annotations are placed after the file comment (if any) and before package, and separated by an empty line so it’s visually obvious that the annotation applies to the file, not to the package.

Example of an “exported API” file

Suppose we want to collect in one place the functions that build report strings. Let’s create a file ExpenseApi.kt:

@file:JvmName("ExpenseApi")

package app.expenses

fun formatMoney(amount: Int): String {
    return "$amount ₣ "
}

fun formatExpenseLine(title: String, amount: Int): String {
    return "$title: ${formatMoney(amount)}"
}

Notice two things.

First, @file:JvmName("ExpenseApi") is at the very top and sets the JVM name of the file class. This placement style for file annotations is considered correct and expected.

Second, we didn’t create any classes by hand. We’re still in the “pre-OOP” part of the course: only functions and collections.

How this looks conceptually

If you imagine how Java will see this file, the idea is:

flowchart TD
    A["ExpenseApi.kt top-level fun"] --> B["JVM class (facade)"]
    B --> C["Java calls static methods"]
    B["JVM class name = ExpenseApi"] --> C

Without @file:JvmName the JVM class would almost certainly be named ExpenseApiKt (because the file is ExpenseApi.kt). With the annotation it becomes simply ExpenseApi.

And yes, this is exactly the case where “we’re not writing Java”, but we’re making sure a Java colleague doesn’t have to see the Kt suffix every day and remember what it is.

3. When a property becomes a field: @JvmField

Why val is usually not a “field”

When you write:

val appName: String = "Budget CLI"

in Kotlin it looks like a “variable/constant”. But on the JVM a property typically turns into:

1) a field (where the value is stored),
2) a getter method getAppName() (and for var also a setter setAppName(...)).

That is, by default Java interacts with a property via methods, not via direct field access. This matches encapsulation well and the fact that Kotlin properties can have custom getters/setters.

And here an interop nuance appears: if you want Java to see your value as a “simple field” (for example, as a constant or a public flag), then accessing it via getX() may feel unnecessarily verbose, and sometimes it also clashes with coding style.

@JvmField and applicability boundaries

Sometimes you really want: “let this be a public field, without getters and setters”. That’s what the @JvmField annotation is for.

Its meaning: export a Kotlin property as a JVM field so that Java can access it directly, without getX().

It’s important to state the boundary right away: @JvmField mainly makes sense for the sake of a Java consumer. In Kotlin code you still write API_VERSION, DEFAULT_CURRENCY, and for a Kotlin developer almost nothing changes. But for Java the access form changes.

Example: API version and an application “banner”

Let’s add a file InteropConstants.kt to the app.expenses package:

package app.expenses

import kotlin.jvm.JvmField

@JvmField
val API_VERSION: Int = 1

val banner: String
    get() = "Expense CLI (api=$API_VERSION)"

There are two different cases here on purpose.

API_VERSION is a stored value; it has a backing field (an actual storage location). It can be exported as a field.

banner is a computed property: it’s “assembled” by a getter every time. It has no separate storage field, so there is simply nothing to “export as a field”. This is an important idea: @JvmField works only where there is a real field.

How Java will see it

Kotlin declaration What is typically generated on the JVM What happens with @JvmField
val X = 1
field + getX() public field X (no getter)
var X = 1
field + getX() + setX(...) public field X (without accessors)
val X get() = ...
only getX() not possible (no backing field)

This is not a “gentleman’s agreement”, but a direct consequence of how Kotlin maps properties onto the JVM.

4. Mini-embedding into a CLI project: a Java-friendly API without magic

Now there’s an important moment. We won’t turn our project into a world-class library, and we won’t discuss Gradle publishing and other grown-up words. But we will make the code look neat and “export-ready”: a separate API file, a clear JVM name, and a couple of values that can be read as fields.

Let our project be a console expense tracker that stores expenses in a list MutableList<Triple<String, Int, String>>, containing (category, amount, comment).

File with API functions: @file:JvmName

Let’s create ExpenseInterop.kt:

@file:JvmName("ExpenseInterop")

package app.expenses

fun makeExpense(category: String, amount: Int, note: String): Triple<String, Int, String> {
    return Triple(category, amount, note)
}

fun expenseAmount(expense: Triple<String, Int, String>): Int {
    return expense.second
}

Yes, these are simple functions, and a Kotlin developer could just write expense.second everywhere. But the point of an “API file” is that you define a surface that other languages and modules can use.

And yes, we put the file annotation at the top of the file, before package. It’s not just “a convention”; it really affects readability and what the annotation applies to.

File with “public values”: @JvmField

Let’s create ExpenseConfig.kt:

package app.expenses

import kotlin.jvm.JvmField

@JvmField
val DEFAULT_CURRENCY: String = "RUB"

@JvmField
val API_VERSION: Int = 1

fun formatMoney(amount: Int): String {
    return "$amount $DEFAULT_CURRENCY"
}

In Kotlin this will be convenient both as “config” and as a simple way to keep shared values in one place.

If someday Java code wants to know the currency or the API version, it won’t have to call getDEFAULT_CURRENCY() (and then explain to the team lead why a constant looks like a getter). It will be able to access the field.

Verify that the app still works

Let’s update main (simplified snippet — we show the idea, not the entire 200-line project):

package app

import app.expenses.API_VERSION
import app.expenses.formatMoney
import app.expenses.makeExpense

fun main() {
    val expense = makeExpense("food", 350, "lunch")
    println("API v$API_VERSION")                      // API v1
    println("Amount: ${formatMoney(expense.second)}")  // Amount: 350 RUB
}

Notice: for Kotlin code it doesn’t matter at all whether @JvmField and @file:JvmName are present. Kotlin code reads as usual. But the JVM representation becomes cleaner for an external consumer.

5. Typical mistakes

In this topic mistakes are especially tricky: code can look “logical” in Kotlin, but be inconvenient (or even surprising) for the Java world. So it’s better to learn to recognize the classic rakes by their sound right away.

Mistake No. 1: put @file:JvmName in the wrong place — for example, after package.
File annotations apply to the entire file, so they must be placed before package. If you place them lower, the compiler won’t “guess what you meant”, and will plainly tell you it’s not allowed. Keep a simple rule: file annotation at the top of the file, then an empty line, then package. This order is explicitly reflected in the general Kotlin code style conventions.

Mistake No. 2: expect Java to see a top-level function “just by name”, without a class.
On the JVM, functions don’t hang in the air: they will be methods in some class. If you don’t control the file class name, Java will almost certainly see the Kt suffix. That’s normal, but if you are designing an API, it’s better to immediately give it a readable name via @file:JvmName so you don’t live with technical details in the public interface.

Mistake No. 3: try to put @JvmField on a computed property.
If a property has no backing field, then “exporting a field” is physically impossible: there is no storage, only computation logic. This is a common trap because in Kotlin val banner get() = ... looks like a “variable”, but on the JVM it’s a pure method. In that case either keep the normal getter (and Java will call getBanner()) or make it a stored value.

Mistake No. 4: apply @JvmField “just in case”, without understanding why.
@JvmField is not decoration and not a “Kotlin accelerator”. It’s an interop design tool. If your module won’t be used from Java, then most of the time you don’t need to turn properties into fields: getters/setters are a normal and safe form. The annotation is needed when you specifically want to give Java simple direct access.

Mistake No. 5: mix “everything at once” in one file, and then try to give it a nice name for Java.
If you want to export an API surface, it’s useful to keep a separate file (or several) for such functions/values. Then @file:JvmName("ExpenseApi") becomes meaningful: it’s truly an “entry point”. But if the file contains main, parsing, reports, and a random utility trimAndNormalize() all interleaved, then even a perfect JVM name won’t save it — the API will look like an attic where “everything is useful, but it’s scary to walk”.

1
Task
Kotlin SELF, level 29, lesson 4
Locked
Cleaning up negatives
Cleaning up negatives
1
Task
Kotlin SELF, level 29, lesson 4
Locked
Sorting tickets
Sorting tickets
1
Survey/quiz
Java interoperability, level 29, lesson 4
Unavailable
Java interoperability
Java interoperability
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION