Kotlin secondary constructor

ironic picture ironic · Oct 10, 2013 · Viewed 69.8k times · Source

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

Answer

Andrey Breslav picture Andrey Breslav · Oct 11, 2013

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

usage:

val c = C.new("foo")