代码之家  ›  专栏  ›  技术社区  ›  Tobia

Kotlin默认构造函数

  •  0
  • Tobia  · 技术社区  · 8 年前

    这个 docs 说:

    在JVM上,如果主构造函数的所有参数都有默认值,编译器将生成一个额外的无参数构造函数,该构造函数将使用默认值。这使得将Kotlin与通过无参数构造函数创建类实例的库(如Jackson或JPA)一起使用变得更容易。

    但情况似乎并非如此:

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

    我错过了什么?

    1 回复  |  直到 8 年前
        1
  •  5
  •   Ricky Mo    8 年前

    我认为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相同。

    编译 使用无参数构造函数。