简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM