Kotlin secondary constructor Ask Question

Kotlin secondary constructor Ask Question

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) { ... }
}

ベストアンサー1

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


For now Kotlin supports only primary constructors (secondary constructors may be supported later).

セカンダリ コンストラクターのほとんどのユースケースは、以下のいずれかの手法によって解決されます。

テクニック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")

おすすめ記事