0
0
Kotlinprogramming~5 mins

Primary constructor and init blocks in Kotlin

Choose your learning style9 modes available
Introduction

Primary constructors and init blocks help set up an object when you create it. They make sure the object starts with the right values.

When you want to give initial values to an object right when you create it.
When you need to run some setup code as soon as an object is made.
When you want to keep your code simple by combining value setup and extra initialization.
When you want to check or change values before the object is ready to use.
Syntax
Kotlin
class ClassName constructor(parameter1: Type, parameter2: Type) {
    init {
        // code to run when object is created
    }
}

The constructor keyword is optional if there are no annotations or visibility modifiers.

The init block runs every time an object is created, right after the primary constructor.

Examples
Simple class with primary constructor and init block that prints info when a Person is created.
Kotlin
class Person(val name: String, val age: Int) {
    init {
        println("Person created: $name, age $age")
    }
}
Init block calculates area using constructor values and prints it.
Kotlin
class Rectangle(val width: Int, val height: Int) {
    val area: Int
    init {
        area = width * height
        println("Area calculated: $area")
    }
}
Class with empty primary constructor and init block that runs on creation.
Kotlin
class EmptyExample {
    init {
        println("Object created with no parameters")
    }
}
Init block checks the value and prints a warning if it is negative.
Kotlin
class SingleParam(val value: Int) {
    init {
        if (value < 0) {
            println("Warning: value is negative")
        }
    }
}
Sample Program

This program creates two Car objects. The init block prints details and warns if the year is before 1886, when cars were invented.

Kotlin
class Car(val brand: String, val year: Int) {
    init {
        println("Creating a car: $brand from year $year")
        if (year < 1886) {
            println("Warning: Cars were not invented before 1886!")
        }
    }
}

fun main() {
    println("Start program")
    val car1 = Car("Toyota", 2020)
    val car2 = Car("Ford", 1800)
    println("End program")
}
OutputSuccess
Important Notes

Time complexity: The init block runs once per object creation, so O(1) time per object.

Space complexity: No extra space beyond the object itself is used by init blocks.

Common mistake: Trying to use uninitialized properties inside init blocks before they are set.

Use init blocks when you need to run extra setup code beyond just assigning constructor parameters.

Summary

Primary constructors set initial values when creating an object.

Init blocks run right after the primary constructor to do extra setup.

Use them together to keep object creation simple and clear.