-
Notifications
You must be signed in to change notification settings - Fork 23
Using @JvmOverloads in kotlin
Devrath edited this page Oct 12, 2023
·
2 revisions
- We know that
java
andkotlin
are interoperable. This means we can communicate fromjava
tokotlin
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 theparameters
, Now if we access this in kotlin class and do not pass a value to thedefault
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 aboutmissing 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 ofJava
class 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");
}
}