In Kotlin, a class can have one primary constructor and an unlimited number of secondary constructors. The difference from Java is that in Kotlin, the primary constructor is declared in the class header and can contain parameters and modifiers. Secondary constructors must always call either another secondary constructor, the primary constructor, or the superclass constructor (using the super keyword).
Key features:
: super(...).super(...) or another secondary/primary constructor.Example of usage with inheritance:
open class A(val a: Int) { constructor(a: Int, str: String) : this(a) { println("Secondary in A: $str") } } class B : A { constructor(a: Int) : super(a) { println("Secondary in B") } constructor(a: Int, s: String) : super(a, s) { println("Secondary #2 in B") } }
How the approach differs from Java:
Is it possible in Kotlin to create a derived class without explicitly calling the superclass constructor, if there is only a specific constructor in the base class?
Answer: No, unlike Java, in Kotlin, calling the superclass constructor is mandatory and is explicitly specified either in the "head" of the class or after the : super() keyword.
Example of an error:
open class Base(val x: Int) class Derived : Base // Compilation error!
Story
In a microservice project after migrating to Kotlin, they forgot to explicitly specify the parent constructor: the superclass constructor with a mandatory parameter was not called, the service did not compile, and refactoring of signatures was required.
Story
An Android project had a deep hierarchy (Activity → BaseActivity → CustomActivity), adding a secondary constructor lost parameters, leading to a call to the wrong base constructor, leaving some fields null — the application crashed at runtime with NPE.
Story
In open library code, a secondary constructor in the child class accidentally bypassed the primary constructor, leading to two different initialization branches: sometimes the field was initialized, sometimes it was not. The error was discovered only after a long time due to complex bug reports.