Kotlin default constructor

2019-08-26 04:09发布

问题:

The docs say:

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.

But this does not appear to be the case:

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

What am I missing?

回答1:

I think the REPL runs the kotlin code as script, which does not compile completely.

When running 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)
}

with

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

it correctly prints

public A(int,int,int,kotlin.jvm.internal.DefaultConstructorMarker)
public A()
public A(int,int)

When running test.kts:

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

with

kotlinc -script test.kts

it prints

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

same as REPL.

So it should be safe to say that it does compile with the parameterless constructor.