skip to content
blog.metters.dev

TIL about @JvmOverloads annotation

/ 2 min read

Kotlin is a tempting alternative as JVM language to Java. Some might even consider it a valid successor. One particularly attractive feature is that both languages are interoperable. This means one project can contain classes written in both languages and they can call each others methods and constructors. Kotlin does not only offer a different syntax, but also named parameters and default values for parameters. But how can Java-Code call constructors with default parameters (written in Kotlin), if they do not exist from the Java/JVM point of view? An additional constructor must be added.

This is solved the same way Lombok makes it possible to remove methods and constructors from source code. The necessary code is added during compile time with the help of an annotation: @JvmOverloads.


[JvmOverloads] instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values.

Source: official documentation


The following snippet shows two classes in Kotlin, one of which has the @JvmOverloads annotation

data class Person @JvmOverloads constructor(
val firstName: String,
val lastName: String,
val age: Int,
val city: String? = null,
)
data class Car(
val manufacturer: String,
val production: Year,
val placeOfRegistration: String? = null,
)

This is a Java class. The second line in the body is commented out, because the compiler would throw an error, due to a missing parameter.

public class Main {
public static void main(String[] args) {
System.out.println(new Person("John", "Doe", 28));
// System.out.println(new Car("Volvo", Year.of(2022)));
System.out.println(new Car("Volvo", Year.of(2022), "Berlin"));
}
}

Click here to see what the class Person would look like, if it was written in Java.

class Person {
private String firstName;
private String lastName;
private int age;
private String city;
public Person(String firstName, String lastName, int age, String city) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.city = city;
}
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.city = null; // <===== default parameter
}
//... getters and setters
}


Resources