在Kotlin中调用另一个构造函数

在Kotlin中,当一个类有多个构造函数时,我们怎样才能从另一个构造函数中调用指定的 (来自iOS世界,我找不到更好的名字)构造函数。

让我给你看一个例子

final class LoadingButton: LinearLayout { var text:String? = null constructor(context: Context, text: String) : this(context) { this.text = text } constructor(context: Context) : super(context) { val t = this.text this.view { button(t) { /* ... */} } } } 

在这里,如果我做loadingButton("TEST", {})该字符串不会传播到按钮,因为this(context)之前调用的便利构造函数的代码(对不起)。

Kotlin能解决这个问题吗? 就像是

 constructor(context: Context, text: String) { this.text = text this(context) } 

编辑

只是为了澄清这个想法,因为它被问到,这个想法是在一个活动中写这样的事情:

 onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) verticalLayout { loadingButton("Some text") //or loadingButton() { this.text = "Some text"} } 

这显然不是很有用,但你明白了。 文本属性可以在施工或以后的时候知道。

这是特别没有用的,因为Kotlin具有参数的默认值,但我正在研究语言并遇到这个问题。

编辑2

另一个解释是,我正在使用loadingButton的布局,所以loadingButton方法如下所示:

 inline fun ViewManager.loadingButton() = loadingButton { } inline fun ViewManager.loadingButton(init: LoadingButton.() -> Unit) = ankoView({ LoadingButton(it) }, init) inline fun ViewManager.loadingButton(text: String, init: LoadingButton.() -> Unit) = ankoView({ LoadingButton(it, text) }, init) 

在JVM上不能存在调用构造函数的代码,因为你对类本身做任何事情之前你必须调用super(...) 。 想想看,如果超类包含一个私人领域,你将不得不初始化它,然后才能使用它。

这通常不是问题,因为您可以通过其他方式调用构造函数:

 constructor(context: Context, text: String?) : super(context) { this.text = text this.view { button(text) { /* ... */} } } constructor(context: Context) : this(context, null) constructor(context: Context, text: String) : this(context, text) 

上面的代码与默认参数大致相同:

 constructor(context: Context, text: String? = null) : super(context) { this.text = text this.view { button(text) { /* ... */} } } 

为了使这个代码惯用(和简洁),使用一个主要的构造函数:

 class LoadingButton(context: Context, val text: String? = null): LinearLayout(context) { init { this.view { button(text) { /* ... */} } } } 

术语如下:指定 – 小学,便利 – 中学

有关更多详细信息,请参阅类和继承 – Kotlin编程语言 。