Primary constructors and init blocks help set up an object when you create it. They make sure the object starts with the right values.
Primary constructor and init blocks in 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.
class Person(val name: String, val age: Int) { init { println("Person created: $name, age $age") } }
class Rectangle(val width: Int, val height: Int) { val area: Int init { area = width * height println("Area calculated: $area") } }
class EmptyExample { init { println("Object created with no parameters") } }
class SingleParam(val value: Int) { init { if (value < 0) { println("Warning: value is negative") } } }
This program creates two Car objects. The init block prints details and warns if the year is before 1886, when cars were invented.
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") }
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.
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.