Kotlin 二级构造函数 [英] Kotlin secondary constructor

查看:36
本文介绍了Kotlin 二级构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I declare a secondary constructor in Kotlin?

是否有任何相关文档?

以下不编译...

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

推荐答案

更新:自 M11 (0.11.*) Kotlin 支持 二级构造函数.

Update: Since M11 (0.11.*) Kotlin supports secondary constructors.

目前 Kotlin 仅支持主构造函数(稍后可能会支持辅助构造函数).

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:

技术 1.(解决您的情况)在您的类旁边定义一个工厂方法

Technique 1. (solves your case) Define a factory method next to your class

fun C(s: String) = C(s.length)
class C(a: Int) { ... }

用法:

val c1 = C(1) // constructor
val c2 = C("str") // factory method

技巧 2.(也可能有用)定义参数的默认值

Technique 2. (may also be useful) Define default values for parameters

class C(name: String? = null) {...}

用法:

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

技巧 3.(当你需要封装时)使用在伴随对象中定义的工厂方法

Technique 3. (when you need encapsulation) Use a factory method defined in a companion 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 companion object:

class C private (s: Int) {
    companion object {
        fun new(s: String) = C(s.length)
    }
}

用法:

val c = C.new("foo")

这篇关于Kotlin 二级构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆