A secondary constructor is declared inside a Kotlin class with the constructor keyword. Kotlin uses it when a class needs additional construction paths, especially when matching a Java or framework superclass that exposes multiple constructors. section 4.2 section 4.2.2
Delegating to superclass and sibling constructors
open class Downloader { constructor(url: String?) { /* ... */ } constructor(uri: URI?) { /* ... */ } } class MyDownloader : Downloader { constructor(url: String?) : this(URI(url)) constructor(uri: URI?) : super(uri) } The URI overload delegates to the superclass with super(uri). The String overload delegates to the other constructor with this(URI(url)); that path eventually initializes the superclass. When no primary constructor exists, every secondary constructor must either delegate to another constructor or initialize the base class. section 4.2.2
Multiple secondary constructors are less common in Kotlin than in Java because default parameter values and named arguments usually replace overloads. Use secondary constructors when distinct initialization paths are required, rather than merely to supply defaults. section 4.2.2
class MyDownloader : Downloader {
constructor(url: String?) : this(URI(url)) #1
constructor(uri: URI?) : super(uri)
}
This compact listing shows a secondary constructor delegating to another constructor with this and the final constructor calling the superclass with super. section 4.2.2
