Update : Since M11 (0.11. *), Kotlin supports secondary constructors .
Kotlin now only supports primary constructors (secondary constructors may be supported later).
Most use cases for secondary designers are solved in one of the following ways:
Technique 1. (solves your case) Define a factory method next to your class
fun C(s: String) = C(s.length) class C(a: Int) { ... }
using:
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) {...}
using:
val c1 = C("foo") // parameter passed explicitly val c2 = C() // default value used
Note that the default values ββwork for any function, not just for constructors.
Technique 3. (when you need encapsulation) Use the factory method defined in the companion object
Sometimes you need your private constructor and only the factory method available to clients. So far, this is only possible with the factory method defined in the companion object :
class C private (s: Int) { companion object { fun new(s: String) = C(s.length) } }
using:
val c = C.new("foo")
Andrey Breslav Oct 11 '13 at 5:18 2013-10-11 05:18
source share