Primary constructor and init blocks in Kotlin - Time & Space Complexity
We want to understand how the time it takes to create an object grows when using primary constructors and init blocks in Kotlin.
How does the number of steps change as we add more properties or logic inside the init block?
Analyze the time complexity of the following code snippet.
class Person(val name: String, val age: Int) {
init {
println("Creating person: $name, age $age")
}
}
fun main() {
val people = List(1000) { Person("Name$it", it) }
}
This code creates 1000 Person objects using a primary constructor and an init block that prints a message for each object.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating each Person object and running its init block.
- How many times: The init block runs once per object, so 1000 times in this example.
Each new object requires running the constructor and init block once, so the total steps grow directly with the number of objects.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 constructor + 10 init calls = 20 steps |
| 100 | 100 constructor + 100 init calls = 200 steps |
| 1000 | 1000 constructor + 1000 init calls = 2000 steps |
Pattern observation: The total work doubles the input size because each object triggers one constructor and one init block call.
Time Complexity: O(n)
This means the time to create objects grows linearly with the number of objects created.
[X] Wrong: "The init block runs only once no matter how many objects are created."
[OK] Correct: Each object creation triggers its own init block, so it runs once per object, not just once total.
Understanding how constructors and init blocks affect performance helps you write efficient Kotlin classes and shows you can reason about object creation costs.
"What if the init block contained a loop that runs m times? How would the time complexity change with respect to n and m?"
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
