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.
Practice
init block in a Kotlin class with a primary constructor?Solution
Step 1: Understand the role of primary constructor
The primary constructor initializes the properties of the class when an object is created.Step 2: Identify the purpose of the init block
The init block runs immediately after the primary constructor to execute extra setup code or validations.Final Answer:
To run additional code right after the primary constructor initializes properties -> Option BQuick Check:
Init block = extra setup after constructor [OK]
- Confusing init block with secondary constructor
- Thinking init block declares constants
- Assuming init block overrides superclass methods
name and age in Kotlin?Solution
Step 1: Recall Kotlin primary constructor syntax
Primary constructor parameters are declared in parentheses after the class name, separated by commas, with types after colons.Step 2: Check each option
class Person(name: String, age: Int) { } uses correct syntax: parentheses, commas, colons for types. Options A, B, and D have syntax errors.Final Answer:
class Person(name: String, age: Int) { } -> Option AQuick Check:
Primary constructor = class Name(params) [OK]
- Using semicolons instead of commas
- Omitting colons before types
- Confusing primary with secondary constructor syntax
class User(val name: String) {
init {
println("Welcome, $name!")
}
}
fun main() {
val user = User("Anna")
}Solution
Step 1: Understand object creation and init block
When creating User("Anna"), the primary constructor sets name to "Anna" and then the init block runs.Step 2: Analyze the init block output
The init block prints "Welcome, $name!" where $name is replaced by "Anna".Final Answer:
Welcome, Anna! -> Option DQuick Check:
Init block prints welcome message with name [OK]
- Expecting no output because println is inside class
- Confusing variable interpolation syntax
- Thinking init block runs only on demand
class Product(val id: Int) {
init {
println("Product ID: $productId")
}
}Solution
Step 1: Check variable usage in init block
The init block tries to printproductId, but the class has onlyiddeclared.Step 2: Confirm variable declaration
SinceproductIdis not declared anywhere, this causes a compilation error.Final Answer:
VariableproductIdis not declared -> Option CQuick Check:
Use declared property names in init block [OK]
- Assuming init block can't use println
- Thinking primary constructor must be empty
- Believing secondary constructor is mandatory
Employee with a primary constructor that takes name and salary. You also want to print a welcome message and calculate a 10% bonus right after object creation. Which is the best way to do this?Solution
Step 1: Understand primary constructor role
Primary constructor is for receiving parameters and initializing properties simply.Step 2: Use init block for extra setup
Init block runs after constructor to print messages and calculate bonus, keeping code organized.Step 3: Evaluate other options
Secondary constructors are unnecessary here; code can't go inside constructor parentheses; companion object is unrelated.Final Answer:
Use primary constructor for parameters and an init block to print message and calculate bonus -> Option AQuick Check:
Primary constructor + init block = clean setup [OK]
- Trying to put logic inside constructor parentheses
- Using secondary constructors unnecessarily
- Misusing companion object for instance initialization
Ready to prove it?
Pass the test and this pattern moves unknown
