Secondary constructors in Kotlin - Time & Space Complexity
Let's see how the time it takes to run code with secondary constructors changes as we create more objects.
We want to know how the number of objects affects the work done during construction.
Analyze the time complexity of the following code snippet.
class Person {
var name: String
var age: Int
constructor(name: String) {
this.name = name
this.age = 0
}
constructor(name: String, age: Int) {
this.name = name
this.age = age
}
}
fun createPeople(n: Int): List {
val list = mutableListOf()
for (i in 1..n) {
list.add(Person("Person $i", i))
}
return list
}
This code defines a class with two ways to create objects and then makes a list of many such objects.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that creates and adds each Person object to the list.
- How many times: Exactly n times, once for each Person created.
Each new person means one more object created and added to the list.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 creations and additions |
| 100 | 100 creations and additions |
| 1000 | 1000 creations and additions |
Pattern observation: The work grows directly with the number of people created.
Time Complexity: O(n)
This means if you double the number of people, the time to create them roughly doubles too.
[X] Wrong: "Secondary constructors make object creation slower in a way that changes time complexity."
[OK] Correct: Secondary constructors just offer different ways to build objects, but creating each object still takes constant time, so total time grows linearly with the number of objects.
Understanding how object creation scales helps you explain performance clearly and shows you know how constructors affect program speed.
What if we added a loop inside the constructor that runs m times? How would the time complexity change?
Practice
secondary constructor in Kotlin?Solution
Step 1: Understand constructors in Kotlin
Kotlin classes can have a primary constructor and one or more secondary constructors to create objects.Step 2: Role of secondary constructors
Secondary constructors allow creating objects with different sets of parameters, providing flexibility.Final Answer:
To provide additional ways to create an object with different parameters -> Option CQuick Check:
Secondary constructors = multiple ways to create objects [OK]
- Thinking secondary constructors replace the primary constructor
- Confusing constructors with functions
- Assuming secondary constructors create static methods
Solution
Step 1: Recall Kotlin secondary constructor syntax
Secondary constructors use the keywordconstructorfollowed by parameters and a body.Step 2: Check each option
constructor(name: String) { this.name = name } uses correct syntax:constructor(name: String) { ... }. Others use invalid keywords.Final Answer:
constructor(name: String) { this.name = name } -> Option DQuick Check:
Keyword 'constructor' starts secondary constructors [OK]
- Adding 'fun' before constructor
- Using 'secondary' keyword
- Confusing with init blocks
class Person(val name: String) {
var age: Int = 0
constructor(name: String, age: Int) : this(name) {
this.age = age
}
}
fun main() {
val p = Person("Alice", 30)
println("Name: ${p.name}, Age: ${p.age}")
}Solution
Step 1: Understand constructor calls
The secondary constructor calls the primary constructor withthis(name), initializingname.Step 2: Assign age in secondary constructor
The secondary constructor setsthis.age = age, soagebecomes 30.Final Answer:
Name: Alice, Age: 30 -> Option BQuick Check:
Secondary constructor sets age correctly [OK]
- Assuming age stays 0
- Thinking name is empty
- Expecting compilation error
class Car(val model: String) {
constructor(model: String, year: Int) {
println("Year: $year")
}
}Solution
Step 1: Check secondary constructor rules
In Kotlin, a secondary constructor must delegate to the primary constructor using: this(...).Step 2: Analyze given code
The secondary constructor does not callthis(model), so it violates the rule.Final Answer:
Secondary constructor must call the primary constructor -> Option AQuick Check:
Secondary constructors require delegation [OK]
- Forgetting to delegate to primary constructor
- Trying to assign val property directly
- Thinking println is disallowed
Book with a primary constructor that takes title and a secondary constructor that also takes author. The secondary constructor should reuse the primary constructor and set author. Which code correctly implements this?Solution
Step 1: Check primary constructor and property initialization
class Book(val title: String) { var author: String = "Unknown" constructor(title: String, author: String) : this(title) { this.author = author } } defines primary constructor withtitleand a mutableauthorproperty with default value.Step 2: Verify secondary constructor delegates properly
The secondary constructor calls: this(title)to reuse primary constructor and setsauthorinside its body.Final Answer:
class Book(val title: String) { var author: String = "Unknown" constructor(title: String, author: String) : this(title) { this.author = author } } -> Option AQuick Check:
Secondary constructor delegates and sets extra property [OK]
- Not delegating secondary constructor to primary
- Trying to assign val properties
- Missing property initialization
Ready to prove it?
Pass the test and this pattern moves unknown
