Skip to content

Using @JvmOverloads in kotlin

Devrath edited this page Oct 12, 2023 · 2 revisions

Observation

  • We know that java and kotlin are interoperable. This means we can communicate from java to kotlin and vice-versa.
  • In Java we cannot assign a default value to the parameter instead we have multiple constructors for this.
  • In kotlin also we can have multiple constructors but if we have a default value to the parameter.
  • So say we have a kotlin data class and a default value is assigned to one of the parameters, Now if we access this in kotlin class and do not pass a value to the default valued parameter then kotlin provides by its behalf.
  • Now if we use the same data class in java and we do not pass a value, the java compiler will complain about missing argument.
  • To overcome this, We prefix the constructor of the data class with @JvmOverloads as seen in example below, This will instruct the compiler to generate and pass a default value in case of Java class also.

Code

Student.kt

data class Student1(val name: String,val age : Int =  27)
data class Student2 @JvmOverloads constructor(val name: String,val age : Int =  27)

DemoJvmOverloadsAnnotation.kt

public class DemoJvmOverloadsAnnotation {
    public void initiate(){
        Student1 obj1 = new Student1("Karan",29);
        Student2 obj2 = new Student2("Karan");
    }
}
Clone this wiki locally