kotlin - Kotlin默认构造函数

标签 kotlin default-constructor

docs说:

On the JVM, if all of the parameters of the primary constructor have default values, the compiler will generate an additional parameterless constructor which will use the default values. This makes it easier to use Kotlin with libraries such as Jackson or JPA that create class instances through parameterless constructors.



但这似乎并非如此:
Welcome to Kotlin version 1.2.71 (JRE 10.0.2+13-Ubuntu-1ubuntu0.18.04.2)
Type :help for help, :quit for quit
>>> class A(val x: Int = 1, val y: Int = 2)
>>> for (c in A::class.java.constructors) println(c)
public Line_0$A(int,int,int,kotlin.jvm.internal.DefaultConstructorMarker)
public Line_0$A(int,int)
>>> 

我想念什么?

最佳答案

我认为REPL将kotlin代码作为脚本运行,但无法完全编译。

运行test.kt时:

class A(val x: Int = 1, val y: Int = 2)
fun main(args: Array<String>) {
    for (c in A::class.java.constructors) println(c)
}


kotlinc test.kt -include-runtime -d test.jar
kotlin test.jar

它可以正确打印
public A(int,int,int,kotlin.jvm.internal.DefaultConstructorMarker)
public A()
public A(int,int)

运行test.kts时:
class A(val x: Int = 1, val y: Int = 2)
for (c in A::class.java.constructors) println(c)


kotlinc -script test.kts

它打印
public Test$A(int,int,int,kotlin.jvm.internal.DefaultConstructorMarker)
public Test$A(int,int)

与REPL相同。

因此,可以肯定地说它确实可以使用无参数构造函数进行编译。

关于kotlin - Kotlin默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52601611/

相关文章:

c++ - 作为函数参数的字符串对的 C++ vector 的默认规范在 gcc-4.1.2 上无效?

Android Studio Kotlin 通过代码设置 UI 元素

kotlin - 注入(inject)不适用于第二个构造函数

kotlin - Kotlin 中的多平台输入流替代方案?

c# - 为什么在创建带参数的构造函数时默认的无参数构造函数消失

c++ - 当包含方括号时,默认构造函数不会在模板类中编译 (g++4.6.1)

list - Kotlin:检查列表是否具有特定类型的对象

kotlin - kotlin Poet中如何实现 suspend 关键字修改高阶函数

c++ - 具有引用数据成员的类的默认构造函数?

c++ - 使用一元调整大小减小非默认可构造元素的容器大小