Kotlin中次构造函数的语法

3

我有这段代码片段,它将演示构造函数执行的顺序:

fun main(args: Array<String>) {
    Sample("T","U")
}

class Sample(private var s : String) {
    constructor(t: String, u: String) : this(t) { // I don't get what "this(t)" is!
        this.s += u
    }
    init {
        s += "B"
    }
}

在次构造器声明中的": this(t)"是什么意思?

这不是返回类型吗?难道不是吗?

3个回答

4

在这种情况下,this是一个关键字,它委托给主构造函数。当你的类有多个主构造函数时,在Kotlin中它是强制性的。Java的等价语句是:

class Simple {
  private String s;
  public Simple(String s) { // Here is your primary constructor
     this.s = s;
  }
  public Simple(String t, String u) { // Here is your secondary constructor 
     this(t);
     this.s += u;
  }
  {
     s += "B"; // Here is the init block
  }
}

2

使用

this(t)

你调用主构造函数并将 t 作为 s 的参数传递。 你甚至可以写成这样:

this(s = "a")

然后你将 s 设置为 "a"。 因此,顺序是:主构造函数、init、次构造函数。更多详情请查看:https://kotlinlang.org/docs/reference/classes.html


2
除了答案之外,这是调用默认主构造函数所必需的内容:
class Sample(private var s: String) { }

就像在Java中一样:

public Sample(String s) {

}

public Sample(String t, String u) {
    this(t); // invoke constructor Sample(String s)
}

为避免这种调用,您可以这样写:
class Sample {

    private var s = ""

    constructor(t: String) {
        s = ...
    }

    constructor(t: String, u: String) {
        s = ...
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接