CodeGym /Courses /Kotlin SELF /Secondary constructors and this(...) delegation in Kotlin...

Secondary constructors and this(...) delegation in Kotlin

Kotlin SELF
Level 31, Lesson 2
Available

1. Why secondary constructors are needed

When you’re just starting to write classes, it feels like one constructor is more than enough: “well, we always create Expense(title, amount, category)”. And then reality hits: data arrives in different formats. A user enters a number as a string; from the console you get a single line title;amount;category; sometimes you want to make some fields default; and sometimes you need a “short path” like Expense("Coffee", 250), and set the category to a default value.

And that’s usually where two painful scenarios show up.

First: you push parsing and normalization outside, and main() turns into a place where input, parsing, validation, error messages, and “add to list” logic all live together. You get a “combine harvester” that’s hard to read and even harder to maintain.

Second: you try to “fit everything” into the primary constructor, add a bunch of parameters (String?, flags, defaults), and the constructor goes from a “clean entry point” to a “buffet”: you can take anything, but it’s unclear what you’ll get out.

Secondary constructors are the third path: keep the primary constructor strict and clear, and implement additional creation methods as “adapters” that bring input into the correct form.

Kotlin explicitly describes secondary constructors as additional initialization paths, useful when you need multiple ways to create an object.

2. Basics: syntax and delegation

How a secondary constructor is declared

A secondary constructor is declared inside the class body and starts with the keyword constructor. It has parameters and (usually) a body in { ... }.

The most important part is this(...). This is constructor delegation: we’re saying “create the object via another constructor of this same class” (usually via the primary one). If a primary constructor exists, secondary constructors must delegate to it (directly or through other secondary ones), so that the overall initialization path is unified.

A minimal “format adaptation” example:

class User(val name: String, val age: Int) {

    constructor(name: String, ageText: String) : this(
        name = name,
        age = ageText.toIntOrNull() ?: 0
    )
}

fun main() {
    val u1 = User("Ann", 20)
    val u2 = User("Bob", "18")
    val u3 = User("Eve", "oops")

    println("${u1.name} ${u1.age}") // Ann 20
    println("${u2.name} ${u2.age}") // Bob 18
    println("${u3.name} ${u3.age}") // Eve 0
}

Notice: the secondary constructor here does not “duplicate” object creation. It converts ageText: String into age: Int and delegates further.

Secondary constructor as an adapter, not a second “factory”

It’s very tempting to start writing “real initialization” inside a secondary constructor: validation, normalization, complex conditions, assignments. But if you do that, you effectively build two different roads to object creation—and they will start to diverge in rules.

Today you call trim() in one constructor; tomorrow you forget it in another; the day after tomorrow you add a new check in only one—and now the same class behaves differently depending on which constructor created it. That’s unpleasant even without obvious bugs; it’s simply hard to read such code.

A practical mental model:

Primary constructor + init is the “single factory” that produces valid objects.

Secondary constructors are “intake points” that accept input in different forms and bring it to the factory standard.

If you want to see it as a diagram:

flowchart TD
    A["Raw input (strings, CSV, partial data)"] --> B["Secondary constructor (adapter)"]
    B --> C["Primary constructor + init (single set of rules)"]
    C --> D["Finished valid object"]

The point is not only “architectural beauty”. Delegation into the primary constructor guarantees that the shared initialization code (including init blocks and property initializers) runs consistently.

Direct and indirect delegation

In real life, a class can have multiple secondary constructors. Sometimes it’s convenient for one secondary constructor to delegate to another, and only then to the primary. That’s indirect delegation, and Kotlin considers it normal: the key is that you eventually reach the primary (if it exists).

Let’s compare two kinds of delegation with a simple example:

class Point(val x: Int, val y: Int) {

    // direct delegation to primary
    constructor(x: Int) : this(x, 0)

    // indirect delegation: first to constructor(x: Int), then to primary
    constructor() : this(0)
}

fun main() {
    println("A: ${Point(5, 7).x}, ${Point(5, 7).y}") // A: 5, 7
    println("B: ${Point(5).x}, ${Point(5).y}")       // B: 5, 0
    println("C: ${Point().x}, ${Point().y}")         // C: 0, 0
}

Why is this convenient? Because sometimes you want to express the rule “if y isn’t specified—use 0”, and “if nothing is specified at all—both x and y equal 0”. A delegation chain lets you avoid repeating these rules.

3. Case study: Expense in an expense tracker

Now let’s implement the application that evolves throughout the course: a simple console expense tracker (the hypothetical BudgetBuddy).

The problem we run into: in a CLI, the user enters data as strings. That means somewhere we need to do trim(), toIntOrNull(), checks like “blank/not blank”, “amount > 0”. If we keep this outside, main() will bloat. If we cram many input variants into the primary constructor, it becomes muddy.

So we’ll do this:

  • The primary constructor Expense(...) accepts already-normalized values.
  • Secondary constructors accept raw input and convert it into a normal form.

Primary constructor and init: a single set of correctness rules

Let’s start with the primary constructor and init. init is a convenient place to validate via require(...).

class Expense(
    val title: String,
    val amount: Int,
    val category: String
) {
    init {
        require(title.isNotBlank()) { "title must not be blank" }
        require(amount > 0) { "amount must be > 0, got $amount" }
        require(category.isNotBlank()) { "category must not be blank" }
    }

    override fun toString(): String = "$title: $amount [$category]"
}

The checks here are simple: empty strings are forbidden; the amount must be positive. This is our invariant: an expense object must not exist in a meaningless state like “empty title, amount -500”.

Secondary constructor: accept strings and normalize

Now let’s add a convenient way to create an Expense from strings, as if they came from readln(). Here the secondary constructor will do three things: trim(), parse amount, and delegate to the primary constructor.

Important: we’re not turning the secondary constructor into a “monster”; it stays an adapter. The “main rules” still live in init.

class Expense(
    val title: String,
    val amount: Int,
    val category: String
) {
    constructor(titleInput: String, amountText: String, categoryInput: String) : this(
        title = titleInput.trim(),
        amount = amountText.trim().toIntOrNull() ?: 0,
        category = categoryInput.trim()
    )

    init {
        require(title.isNotBlank()) { "title must not be blank" }
        require(amount > 0) { "amount must be > 0, got $amount" }
        require(category.isNotBlank()) { "category must not be blank" }
    }

    override fun toString(): String = "$title: $amount [$category]"
}

If a person enters amountText = "oops", then toIntOrNull() returns null, we substitute 0, and then init “fails” expense creation via require(amount > 0). This is fail-fast behavior: the object is not created because the input is invalid.

Another format: one line title;amount;category

In console utilities, you often want to shorten input. For example, a command might look like: add Coffee;250;food.

That is, the user enters a single line, and we parse it. Let’s do the minimal thing: split(';'), check the number of parts, and delegate again.

Since a constructor can’t “return null”, you have to choose a strategy: either set defaults (dangerous), or fail via require. For a learning project and correctness discipline, failing is better.

class Expense(
    val title: String,
    val amount: Int,
    val category: String
) {
    constructor(line: String) : this(
        titleInput = line.split(';').getOrNull(0) ?: "",
        amountText = line.split(';').getOrNull(1) ?: "0",
        categoryInput = line.split(';').getOrNull(2) ?: ""
    )

    constructor(titleInput: String, amountText: String, categoryInput: String) : this(
        title = titleInput.trim(),
        amount = amountText.trim().toIntOrNull() ?: 0,
        category = categoryInput.trim()
    )

    init {
        require(title.isNotBlank()) { "title must not be blank" }
        require(amount > 0) { "amount must be > 0, got $amount" }
        require(category.isNotBlank()) { "category must not be blank" }
    }

    override fun toString(): String = "$title: $amount [$category]"
}

There’s a “suspicious spot” here: line.split(';') is called three times. We could optimize, but for now we choose simplicity and readability. The goal right now is to avoid code that looks like a spell in an ancient language.

Notice the chain: constructor(line) delegates to constructor(titleInput, amountText, categoryInput), and that delegates to the primary constructor. This is exactly indirect delegation.

What it looks like in main()

When secondary constructors are done correctly, main() starts to look simpler: it chooses “which way to create an object”, but it doesn’t constantly do trim() and toIntOrNull().

Mini demo:

fun main() {
    val expenses = mutableListOf<Expense>()

    val e1 = Expense("Coffee", 250, "food")
    val e2 = Expense("  Taxi  ", "510", " transport ")
    val e3 = Expense("Pizza;900;food")

    expenses.add(e1)
    expenses.add(e2)
    expenses.add(e3)

    expenses.forEach { println(it) }
    // Coffee: 250 [food]
    // Taxi: 510 [transport]
    // Pizza: 900 [food]
}

main() almost doesn’t know how data is normalized. It says: “create an expense”, and the class itself guarantees that the expense will be valid—or it won’t be created at all.

4. What to avoid in secondary constructors

Secondary constructors are easy to turn into a place where “everything happens”. But if you want the class to remain predictable, it helps to keep in mind a few language constraints and a few common-sense constraints.

From the language perspective: if a class has a primary constructor, a secondary must delegate to it directly or indirectly. This rule helps avoid a situation where one initialization branch bypasses shared code.

From the design perspective: if you find that your secondary constructor contains 30 lines of logic, lots of if/else, and also “just a bit of console printing for debugging”, you’re probably building a second factory for creating objects. This isn’t “forbidden”, but it almost certainly leads to rule drift.

And one more practical point: when you create an object via a secondary constructor, delegation runs first (primary + init), and only then does the body of the secondary run. So don’t assume the secondary body is “the very beginning of the object’s life”. It’s more like “an additional step after the base initialization”.

5. Common mistakes

Mistake No. 1: duplicating validations in every secondary constructor.
A common student approach is: check one thing in the primary, check something else in the second constructor, and in the third one forget to check at all. A week later you add a new rule (“category cannot be blank”) and start remembering where else you need to add require. The fix is simple: shared correctness rules live in one place—in init (or next to the primary), and the secondary constructors only bring input into the required form.

Mistake No. 2: trying to “bypass” the primary constructor and assemble the object in pieces.
Sometimes you want to write a secondary constructor that doesn’t delegate via this(...), and instead just assigns fields. In Kotlin, if a primary constructor exists, you can’t do that: a secondary constructor must delegate to the primary (directly or indirectly).
In practice, that’s a good thing: the language forces you to keep a single initialization path and not create “secret entrances” into the class.

Mistake No. 3: making a secondary constructor too “smart” and turning it into a scenario.
A secondary constructor is a bad place for complex branching like “if the command is this—do that, otherwise do something else”. That kind of code usually belongs not to object creation, but to application logic (for example, parsing CLI commands). If you cram it into a constructor, the object starts to “know” too much about the outside world, and the class becomes hard to test and read.

Mistake No. 4: using “magic defaults” that create an invalid object.
In the examples above, we did toIntOrNull() ?: 0, and that’s only okay because we then have require(amount > 0). But if you leave defaults like 0, "", "UNKNOWN" without validations, you get an object that technically exists but is semantically invalid. Later such objects “leak” into collections, reports, sorting— and you end up catching bugs far away from where the object was created.

Mistake No. 5: confusing the role of a secondary constructor with default values.
Sometimes people write a secondary constructor where a default parameter in the primary is enough. For example, if the category is almost always "food", it might be better to make category: String = "food" in the primary, rather than adding a separate constructor(title, amount). Secondary constructors are needed when the input form changes, or when you want to express a delegation chain as separate “convenient entry points”, not just substitute a single value.

1
Task
Kotlin SELF, level 31, lesson 2
Locked
Character coordinates
Character coordinates
1
Task
Kotlin SELF, level 31, lesson 2
Locked
Player profile
Player profile
1
Task
Kotlin SELF, level 31, lesson 2
Locked
Station Clock
Station Clock
1
Task
Kotlin SELF, level 31, lesson 2
Locked
Expense from a string
Expense from a string
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION