Kotlin二级构造函数

如何在Kotlin中声明次级构造函数?

有没有关于这个的文件?

以下不编译…

class C(a : Int) { // Secondary constructor this(s : String) : this(s.length) { ... } } 

更新 :由于M11(0.11。*)Kotlin支持二级构造函数


现在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") 

正如文档所指出的那样 ,你可以用这种方法来使用辅助构造器

 class GoogleMapsRestApiClient constructor(val baseUrl: String) { constructor() : this("https://api.whatever.com/") } 

请记住,您必须扩展第一个构造函数的行为。

我刚刚看到这个问题,我想可能还有另一种技术听起来比安德烈提出的更好。

 class C(a: Int) { class object { fun invoke(name: String) = C(name.length) } } 

你可以写如val c:C = C(3)val c:C = C("abc") ,因为invoke方法的工作原理与Scala中的apply方法一样。

更新

到目前为止,二级构造函数已经是语言规范的一部分,所以不应该使用这种解决方法。

为了声明次级构造函数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 
 class Person(val name: String) { constructor(name: String, parent: Person) : this(name) { parent.children.add(this) } } 

你可以试试这个。

下面的代码片段应该工作

 class C(a:Int){ constructor(s:String):this(s.length){..} } 

kotlin次要构造函数示例

 class Person(name: String){ var name="" var age=0 constructor(age :Int,name : String) : this(name){ this.age=age this.name=name } fun display(){ print("Kotlin Secondary constructor $name , $age") } } 

主功能

 fun main(args : Array<String>){ var objd=Person(25,"Deven") objd.display() }