My kotlin file:
class Chat(var name: String, var age: Int? = 18)
My java file only can do this:
new Chat("John",18);
But could i just write this ?
new Chat("John");
The @JvmOverloads annotation is a convenience feature in Kotlin for interoperating with Java code, but there is one specific use case on Android where it shouldn't be used carelessly. Let's first look at what this annotation does, and then get to the specific issue.
A constructor that takes no parameters is called a parameterless constructor. Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new .
A class needs to have a constructor and if we do not declare a constructor, then the compiler generates a default constructor. A class in Kotlin can have at most one primary constructor, and one or more secondary constructors.
In Kotlin, you can provide default values to parameters in function definition. If the function is called with arguments passed, those arguments are used as parameters. However, if the function is called without passing argument(s), default arguments are used.
From Kotlin document:
Normally, if you write a Kotlin method with default parameter values, it will be visible in Java only as a full signature, with all parameters present. If you wish to expose multiple overloads to Java callers, you can use the @JvmOverloads annotation.
So, if you want to initialize Chat
with name
only in Java, you have to add @JvmOverloads
annotation to the constructor.
class Chat @JvmOverloads constructor(var name: String, var age: Int? = 18)
It will generate additional overload for each parameter with a default value.
public Chat(String name) {} public Chat(String name, Integer age) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With