gpt4 book ai didi

kotlin - Kotlin 中辅助构造函数的语法

转载 作者:行者123 更新时间:2023-12-02 09:18:02 25 4
gpt4 key购买 nike

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

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)”是什么?

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

最佳答案

在这种特殊情况下,this 是一个委托(delegate)给主构造函数的关键字。当你的类有多个类时,它在 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
}
}

关于kotlin - Kotlin 中辅助构造函数的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61707922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com