如何在Kotlin中声明二级构造函数?
有关于这方面的文件吗?
以下内容未编译。。。
class C(a : Int) {
// Secondary constructor
this(s : String) : this(s.length) { ... }
}
更新:由于M11(0.11.*)Kotlin支持secondary constructors。
目前,Kotlin只支持主构造函数(稍后可能会支持辅助构造函数)。
二级构造函数的大多数用例通过以下技术之一解决:
技巧1.(解决您的案例)在类旁边定义一个工厂方法
fun C(s: String) = C(s.length)
class C(a: Int) { ... }
用法:
val c1 = C(1) // constructor
val c2 = C("str") // factory method
技术2.(可能也有用)定义参数的默认值
class C(name: String? = null) {...}
用法:
val c1 = C("foo") // parameter passed explicitly
val c2 = C() // default value used
请注意,默认值适用于任何函数,不仅适用于构造函数
技术3.(当需要封装时)使用在伴随对象中定义的工厂方法
有时,您希望构造函数是私有的,并且只有一个工厂方法可供客户端使用。目前,这只能在伴随对象中定义的工厂方法中实现:
class C private (s: Int) {
companion object {
fun new(s: String) = C(s.length)
}
}
用法:
val c = C.new("foo")
作为documentation points,您可以这样使用辅助构造函数
class GoogleMapsRestApi constructor(val baseUrl: String) {
constructor() : this("s://api.whatever/")
}
请记住,必须扩展第一个构造函数行为。
要声明辅助构造函数Kotlin,只需使用构造函数关键字:like
这是一个主构造函数:
class Person constructor(firstName: String) {
}
或
class Person(firstName: String) {
}
对于这样的二级构造函数代码:
class Person(val name: String) {
constructor(name: String, parent: Person) : this(name) {
parent.children.add(this)
}
}
必须调用主构造函数,否则编译器将抛出以下错误
Primary constructor call expected
init
的构造函数:
class PhoneWatcher : TextWatcher {
private val editText: EditText
private val mask: String
private var variable1: Boolean = false
private var variable2: Boolean = false
init {
variable1 = false
variable2 = false
}
constructor(editText: EditText) : this(editText, "##-###-###-####")
constructor(editText: EditText, mask: String) {
this.editText = editText
this.mask = mask
}
...
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(32条)