Kotlin第二构造函数 [英] Kotlin secondary constructor
问题描述
如何在Kotlin中声明辅助构造函数?
有任何文件吗?
以下不能编译...
class C(a:Int){
//辅助构造函数
this(s:String):this(s.length ){...}
}
更新:自M11(0.11。*)Kotlin支持 辅助构造函数 。
=======
辅助构造函数的大多数用例都是通过以下技术之一来解决的:
技巧1 (解决您的情况)在类别旁定义工厂方法
fun C(s:String)= C(s.length)
class C(a:Int){...}
用法:
val c1 = C $ b val c2 = C(str)//工厂方法
(也可能有用)为参数定义默认值
class C(name:String? = null){...}
用法:
val c1 = C(foo)//明确传递的参数
val c2 = C()//使用的默认值
请注意,默认值适用于任何函数,不仅适用于构造函数
技巧3 (当需要封装时)使用类对象中定义的工厂方法
构造函数private和只有一个工厂方法可用于客户端。现在只能使用类对象中定义的工厂方法:
C类(s:Int){
class object {
fun new(s:String)= C(s.length)
}
}
用法:
val c = C .new(foo)
How do I declare a secondary constructor in Kotlin?
Is there any documentation about that?
Following does not compile...
class C(a : Int) {
// Secondary constructor
this(s : String) : this(s.length) { ... }
}
Update: Since M11 (0.11.*) Kotlin supports secondary constructors.
=======
For now Kotlin supports only primary constructors (secondary constructors may be supported later).
Most use cases for secondary constructors are solved by one of the techniques below:
Technique 1. (solves your case) Define a factory method next to your class
fun C(s: String) = C(s.length)
class C(a: Int) { ... }
usage:
val c1 = C(1) // constructor
val c2 = C("str") // factory method
Technique 2. (may also be useful) Define default values for parameters
class C(name: String? = null) {...}
usage:
val c1 = C("foo") // parameter passed explicitly
val c2 = C() // default value used
Note that default values work for any function, not only for constructors
Technique 3. (when you need encapsulation) Use a factory method defined in a class object
Sometimes you want your constructor private and only a factory method available to clients. For now this is only possible with a factory method defined in a class object:
class C private (s: Int) {
class object {
fun new(s: String) = C(s.length)
}
}
usage:
val c = C.new("foo")
这篇关于Kotlin第二构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!