Kotlin默认构造函数 [英] Kotlin default constructor

查看:721
本文介绍了Kotlin默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档说:

在JVM上,如果主构造函数的所有参数都具有默认值,则编译器将生成一个附加的无参数构造函数,该构造函数将使用默认值.这样可以更轻松地将Kotlin与通过无参数构造函数创建类实例的Jackson或JPA之类的库一起使用.

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代码作为脚本运行,无法完全编译.

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

运行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相同.

因此可以肯定地说,它是使用无参数构造函数进行编译的.

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

这篇关于Kotlin默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆