Kotlin default constructor

两盒软妹~` 提交于 2019-12-11 18:28:32

问题


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.



来源:https://stackoverflow.com/questions/52601611/kotlin-default-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!