How to omit the constructor parameter with a default value when calling Kotlin in Java?

neuyuandaima :

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");
BakaWaii :

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) {}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=437240&siteId=1