Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"); 
like image 569
neuyuandaima Avatar asked Aug 14 '17 03:08

neuyuandaima


People also ask

What is @JvmOverloads?

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.

What do you call the constructor that has no parameter?

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 .

Does Kotlin have default constructor?

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.

How do I set a default value in Kotlin?

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.


1 Answers

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) {} 
like image 65
BakaWaii Avatar answered Sep 21 '22 23:09

BakaWaii