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/