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
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.
Click here to see what the class Person
would look like, if it was written in Java.
Resources
- It is always a good idea to check out the official documentation
- The code snippets from above work and can be cloned from GitHub