<

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’re going to explore the @JvmField annotation out of Kotlin.

Kotlin has its approach to classes and properties, which differs from the approach used in Java. The @JvmField annotation makes it possible to achieve compatibility between the two languages.

2. Field Declaration

By default, Kotlin classes do not expose fields, but properties instead.

The language automatically provides backing fields to properties which will store its value in the form of a field:

class CompanionSample {
    var quantity = 0
    set(value) {
        if(value >= 0) field = value
    }
}

This is a simple example, but by using Kotlin’s Decompiler in IntelliJ (Tools > Kotlin > Show Kotlin Decompiler) it will show us how it’d look in Java:

public class JvmSample {
   private int quantity;

   // custom getter

   public final void setQuantity(int value) {
      if (value >= 0) {
         this.quantity = value;
      }
   }
}

However, this doesn’t mean we can’t have fields at all, there are certain scenarios, where it’s necessary. In this case, we can leverage the @JvmField annotation, which instructs the compiler not to generate getters and setters for the property and expose it as a simple Java field.

Let’s have a look at the Kotlin example:

class KotlinJvmSample {
    @JvmField
    val example = "Hello!"
}

And its Java decompiled counterpart – which, indeed, proves that the field was exposed in the standard Java way:

public class KotlinJvmSample {
    @NotNull
    public final String example = "Hello!";
}

3. Static Variables

Another instance where the annotation comes in handy is whenever a property declared in a name object or companion object has a static backing field:

public class Sample {
    public static final int MAX_LIMIT = 20;
}
class Sample {
    companion object {
        @JvmField val MAX_LIMIT = 20
    }
}

4. Usage Exceptions

So far, we’ve discussed situations where we can use the annotation, but there are some restrictions.

Here are some situations where we cannot use the annotation:

  • Private properties
  • Properties with open, override, const modifiers
  • Delegated properties

5. Conclusion

In this quick article, we explored the different ways of using the Kotlin’s @JvmField annotation.

The implementation of all these examples and code snippets can be found in the GitHub project – this is a Maven project, so it should be easy to import and run as it is.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS