liveBook · Manning

Secondary constructor

As explained in Kotlin in Action, 2E

A secondary constructor is an additional Kotlin constructor declared in a class alongside its primary constructor or as the class's constructor form.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains declaration syntax and constructor delegation, but defers broader initialization details to primary constructors and initializer blocks.
Examples
Demonstrates String and URI overloads through Java-style Downloader and MyDownloader classes using this and super delegation.
What it assumes
Assumes familiarity with Kotlin classes and introduces the distinction between primary constructors, secondary constructors, and initializer blocks.
What you can do after
Apply Kotlin secondary-constructor syntax to mirror framework overloads and route initialization through this or super.
How it connects
Connects secondary constructors with primary constructors, default parameter values, named arguments, initializer blocks, and superclass constructors.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.