CodeGym /Courses /Kotlin SELF /init block: normalisation and state preparation

init block: normalisation and state preparation

Kotlin SELF
Level 31, Lesson 1
Available

1. Why init is needed and what it does

When you write a class for the first time, it often feels like a constructor is just “parameters in parentheses”, and everything else happens magically. In practice there is some magic there, but it is controllable: Kotlin gives you a place where you can put code that will run at the moment the object is created. That place is called an init block — a small “kitchen” inside the class where you bring input data into order and prepare the state.

init { ... } is an initialization block that runs when an instance of a class is created, i.e., during execution of the primary constructor. In the Kotlin documentation this is described directly as initializer blocks that are launched during execution of the primary constructor.

The most useful thing about init for a beginner: it helps ensure that an object does not store “dirty” input (spaces, empty strings, wrong format), and that internally everything is always neat and predictable.

A tiny “hands-on” example:

class User(val name: String) {
    init {
        println("Created user: $name")
    }
}

fun main() {
    User("Ann") // Created user: Ann
}

Yes, println in init is not production style, but for learning it clearly shows: the block really runs on creation.

2. Normalisation: why “fix” input when creating an object

Normalisation is when you take input data and bring it to a “canonical” form. In programming it is almost like washing your hands before cooking: sure, you can skip it… but then you will be surprised why everything starts smelling strange.

If you are building a console application (and we are), input often comes from readln(). And readln() reads the world as it is: with spaces, extra newlines, unexpected “ ” instead of a name, and the classic “I definitely entered a number” (nope).

Continuing our learning application

Let’s imagine we are building a small console expense tracker (a hypothetical BudgetBuddy). We have an entity Expense — an expense: category, amount, and note. For now, without a data class (we will get to it later), just a regular class.

Let’s make Expense itself put the data in order:

class Expense(
    categoryInput: String,
    amountInput: Int,
    noteInput: String?
) {
    val category: String
    val amount: Int
    val note: String?

    init {
        category = categoryInput.trim().lowercase()
        amount = amountInput
        val n = noteInput?.trim()
        note = if (n == null || n.isBlank()) null else n
    }
}

Here is the key point: the parameters categoryInput, amountInput, noteInput are just input. But the properties category, amount, note are what will actually be stored in the object. And it is precisely in init that we turn input into state.

Let’s test it with a small main:

fun main() {
    val e = Expense(categoryInput = "  Food  ", amountInput = 250, noteInput = "  coffee ")
    println(e.category) // food
    println(e.note)     // coffee
}

Now any part of the program can rely on category already being without spaces and in a consistent case. This reduces the number of “just in case” checks elsewhere.

3. State preparation: not only “clean up”, but also “assemble”

init is useful not only for trim(). Often an object needs to prepare some additional “internal” values. For example, a string for printing, a short identifier, a normalised version for searching, or a neatly composed title.

It is important not to turn init into a “12-season TV series”: it should be responsible for creating a correct state, not for a business scenario like “go to the internet, fetch the exchange rate, and make a fate-changing decision”.

Let’s add a prepared display text to Expense (conditionally summary). It is computed once during creation and stored as a val:

class Expense(
    categoryInput: String,
    amountInput: Int,
    noteInput: String?
) {
    val category: String
    val amount: Int
    val note: String?
    val summary: String

    init {
        category = categoryInput.trim().lowercase()
        amount = amountInput
        val n = noteInput?.trim()
        note = if (n == null || n.isBlank()) null else n

        summary = if (note == null) {
            "$category: $amount"
        } else {
            "$category: $amount ($note)"
        }
    }
}

fun main() {
    val e = Expense("  Transport ", 120, " metro ")
    println(e.summary) // transport: 120 (metro)
}

Note: we are not doing anything overly complex here, but we gain readability in the rest of the code. Later, when we print a list of expenses, we can print summary without rebuilding the string in ten different places.

4. Two normalisation strategies: “fix” or “reject”

In real projects, you almost always choose one of two philosophies.

The first philosophy is “let’s try to gently fix the input”. For example, trim() for a string is a soft fix: the user entered “ Food ”, you turned it into “food”, and everyone is happy.

The second philosophy is “if the input is bad, do not create the object”. This is the fail-fast approach: “better to crash immediately than to live with garbage inside”.

Kotlin explicitly recommends init as a place for validation and shows an example with require(...).

Let’s implement a soft variant (fix spaces) and a strict variant (reject an empty category).

class Expense(categoryInput: String, val amount: Int) {
    val category: String

    init {
        val fixed = categoryInput.trim().lowercase()
        require(fixed.isNotBlank()) { "Category must not be blank" }
        category = fixed
    }
}

fun main() {
    val e = Expense("  Food  ", 100)
    println(e.category) // food
}

The function require() is a “precondition”: if the condition is false, it throws IllegalArgumentException. We will cover require/check in detail in a separate lecture for this day, but at the init level it is important to remember the idea: input validation logically belongs where the object is created; otherwise you will forever be hunting down who forgot to validate the arguments.

A small table to feel the boundaries:

Situation Usually done in init Why it is convenient
Spaces around a string
trim()
Remove “noise” once rather than at every use site
Different letter case
lowercase()
/
uppercase()
Search/comparison become more stable
Empty string where it is not allowed
require(...)
Better to not create the object than to store broken state
Empty optional note convert to null “No note” and “note = spaces” stop being different worlds

5. Multiple init blocks and execution order

Sometimes you want to split initialization logic into parts: normalisation separately, derived field computation separately, checks separately. Kotlin allows this: there can be multiple init blocks, and they run in declaration order (top to bottom).

It is like cooking dinner: first you take out the ingredients, then wash them, then cut them, then cook. You can do everything in one giant “mega-step”, but it is easier for the brain when steps are separated.

Let’s show the order with an example:

class Demo(categoryInput: String) {
    val category: String = categoryInput.trim()

    init {
        println("init #1: category='$category'")
    }

    init {
        println("init #2: length=${category.length}")
    }
}

fun main() {
    Demo("  Food  ")
    // init #1: category='Food'
    // init #2: length=4
}

The idea to take away: init is not “one magic thing”, but a sequence of blocks. This helps when you read someone else’s code (or your own code three weeks later, which is almost the same).

To visualise the object creation process, it is handy to keep this scheme in mind:

flowchart TD
    A["Called constructor
Demo(' Food ')"] --> B["Property initializers
val category = ..."] B --> C["init #1"] C --> D["init #2"] D --> E["Object is ready for use"]

We will talk about more subtle nuances of initialization order in a separate lecture for this day. For now, it is enough to confidently understand that init happens “on creation” and in order.

6. Design: normalisation inside the class and invariants

Normalisation should live inside the class

A very common beginner “pain” looks like this: you read a string somewhere, do trim() somewhere, forget it somewhere else, and then catch the bug “why is category food not equal to category food ”.

If normalisation lives outside, you must remember it in every place where you create the object. And the number of places will grow over time: an add command, importing from a file, test code, a demo-data generator. And each time, someone will forget.

So a good style guideline sounds like this: the class itself is responsible for keeping its inside clean.

Bad variant (normalisation outside):

fun main() {
    val rawCategory = "  Food  "
    val e = Expense(categoryInput = rawCategory.trim(), amountInput = 100, noteInput = null)
    println(e.category)
}

The problem here is not that it “doesn’t work”. The problem is that in a week someone will create Expense(rawCategory, ...) without trim() and be genuinely surprised.

Good variant (normalisation inside):

fun main() {
    val rawCategory = "  Food  "
    val e = Expense(categoryInput = rawCategory, amountInput = 100, noteInput = null)
    println(e.category) // food
}

Now the object guarantees that category is OK. External code can be simple, and simplicity is an underrated superpower.

init as a “place to assemble invariants”

When you design a class, it is useful to agree with yourself on small rules that always must be true for the object. For example: “category is not empty”, “amount is not negative”, “note is either null or a non-empty string without spaces at the edges”.

Such rules are often called state invariants. You do not have to memorise the term; it is enough to remember the meaning: an object should not exist in a ridiculous form.

init is a great place to “lock in” these rules. Kotlin even hints at this as a typical scenario: init + require(...) to validate data correctness.

In our Expense, let’s enforce two simple ideas: category is not empty, amount is not negative (for now, we simply forbid negative).

class Expense(categoryInput: String, amountInput: Int) {
    val category: String
    val amount: Int

    init {
        val fixedCategory = categoryInput.trim().lowercase()
        require(fixedCategory.isNotBlank()) { "Category must not be blank" }
        require(amountInput >= 0) { "Amount must be >= 0, got $amountInput" }

        category = fixedCategory
        amount = amountInput
    }
}

If someone tries to create Expense(" ", -10), the object simply will not appear. That is much better than creating a “broken” object and then trying to compute reports from it.

7. Typical mistakes when working with init

Mistake #1: normalisation lives outside the class and ends up duplicated.
Usually it starts harmlessly: you did trim() in one place and everything works. Then a second place appears where the object is created; there trim() was forgotten, and search/comparison start behaving “as if Kotlin is joking”. It is better to normalise once in init than to hope for human discipline ten times.

Mistake #2: turning init into “the main application scenario”.
Sometimes in init you want to print a lot, read readln(), compute something big, and do “half the program”. This is bad style: construction should be fast and predictable. init is about state correctness, not about “doing everything at once”.

Mistake #3: mixing the “fix input” and “reject input” strategies without an explicit decision.
If you silently fix some fields (for example, trim()), but other fields suddenly fail with require, users of the class get a strange experience. At the design level it is important, at least for yourself, to choose: “we gently normalise” or “we strictly forbid”, and be consistent.

Mistake #4: making properties var only to change them inside init.
Technically this works, but it often leads to unnecessary mutability: if a property is a var, it means it can be changed after creation — even if that is not part of the meaning. Often it is better to store the normalised result in separate val properties and not let the object “drift”.

Mistake #5: writing checks but with uninformative messages.
require(x > 0) { "bad" } is almost like a note saying “broken” on a broken bridge. A good message should explain the expectation and the actual value. Kotlin and the exception documentation explicitly emphasise that require throws IllegalArgumentException, and the quality of the message determines how quickly you will understand the problem.

1
Task
Kotlin SELF, level 31, lesson 1
Locked
User registration
User registration
1
Task
Kotlin SELF, level 31, lesson 1
Locked
Section label
Section label
1
Task
Kotlin SELF, level 31, lesson 1
Locked
Smart comment
Smart comment
1
Task
Kotlin SELF, level 31, lesson 1
Locked
Two init steps
Two init steps
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION