简体   繁体   English

在Java中调用Kotlin时,如何使用默认值省略构造函数参数?

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

My kotlin file: 我的kotlin档案:

class Chat(var name: String, var age: Int? = 18)

My java file only can do this: 我的java文件只能这样做:

new Chat("John",18);

But could i just write this ? 但我可以写这个吗?

new Chat("John");

From Kotlin document : 来自Kotlin文件

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. 通常,如果您使用默认参数值编写Kotlin方法,则它将仅在Java中显示为完整签名,并且存在所有参数。 If you wish to expose multiple overloads to Java callers, you can use the @JvmOverloads annotation. 如果您希望向Java调用者公开多个重载,则可以使用@JvmOverloads批注。

So, if you want to initialize Chat with name only in Java, you have to add @JvmOverloads annotation to the constructor. 因此,如果要仅使用Java在name初始化Chat ,则必须将@JvmOverloads注释添加到构造函数中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java - 调用构造函数时如何使用类属性中的值 - Java - how to use a value from a class property when calling a constructor Java构造函数的默认参数 - default parameter for java constructor 在Android项目中从Java调用Kotlin函数时,无法省略默认参数 - Can't omit default params when call Kotlin's function from Java in Android project 如何防止Hibernate在解析unsaved-value时调用默认构造函数 - How to prevent Hibernate from calling default constructor when resolving the unsaved-value Kotlin:子构造函数将默认值传递给父 - Kotlin: Child Constructor Passing Default Value to Parent 如何在包含自定义 class 作为参数的 Java 中编写默认构造函数 - How to write a default constructor in Java that contains a custom class as a parameter 在Java中同时调用default和super构造函数 - Calling both the default and super constructor in Java 在Java中省略在子项中使用构造函数 - Omit the use of the constructor in children in Java 从Java调用Kotlin时如何获取错误行号? - How to get the line number of an error when calling Kotlin from Java? 如何在不使用构造函数的情况下在java中为Boolean设置默认值 - how to set default value for Boolean in java without using constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM