-
Notifications
You must be signed in to change notification settings - Fork 24
Using @JvmOverloads in kotlin
Devrath edited this page Oct 12, 2023
·
2 revisions
- We know that
javaandkotlinare interoperable. This means we can communicate fromjavatokotlinand 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
kotlindata class and a default value is assigned to one of theparameters, Now if we access this in kotlin class and do not pass a value to thedefaultvalued parameter then kotlin provides by its behalf. - Now if we use the same
data classin java and we do not pass a value, the java compiler will complain aboutmissing argument. - To overcome this, We prefix the constructor of the
dataclass with@JvmOverloadsas seen in example below, This will instruct the compiler to generate and pass a default value in case ofJavaclass also.
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");
}
}