Generic class declaration in Kotlin - Time & Space Complexity
Let's see how the time needed to create and use a generic class changes as we add more items.
We want to know how the program's work grows when the number of stored items grows.
Analyze the time complexity of the following code snippet.
class Box<T> {
private val items = mutableListOf<T>()
fun add(item: T) {
items.add(item)
}
fun get(index: Int): T {
return items[index]
}
}
This code defines a generic Box class that can hold items of any type. It adds items and gets them by index.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding an item to the list and accessing an item by index.
- How many times: Each add or get is done once per call, no loops inside these methods.
Adding or getting one item takes about the same time no matter how many items are in the box.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 adds = 10 operations |
| 100 | 100 adds = 100 operations |
| 1000 | 1000 adds = 1000 operations |
Pattern observation: The work grows directly with the number of items added, one operation per item.
Time Complexity: O(n)
This means the time to add n items grows in a straight line with n; each item takes about the same time.
[X] Wrong: "Adding an item takes longer as the box gets full because it has to check all items."
[OK] Correct: The list adds items at the end quickly without checking all items, so each add takes about the same time.
Understanding how generic classes handle data helps you explain how your code scales when storing many items, a useful skill in many coding tasks.
"What if the get method searched for an item by value instead of using an index? How would the time complexity change?"
Practice
<T>?Solution
Step 1: Understand generic class declaration
Declaring a generic class with<T>means the class can accept any type as a parameter.Step 2: Identify the benefit
This allows the class to be flexible and reusable for different data types without rewriting the code.Final Answer:
To allow the class to work with any data type without rewriting code -> Option BQuick Check:
Generics = Flexible types [OK]
- Thinking generics restrict types instead of generalizing
- Confusing generics with abstract classes
- Assuming generics create singletons
Box in Kotlin?Solution
Step 1: Recall Kotlin generic syntax
Kotlin uses angle brackets<>to declare generics after the class name.Step 2: Check each option
Onlyclass Box<T> { }is correct, using angle brackets after the class name. The other options use semicolon after <T>, square brackets, or place <T> inside the braces.Final Answer:
class Box<T> { } -> Option CQuick Check:
Generics use <> brackets [OK]
- Using square brackets [] instead of angle brackets
- Adding semicolon after class declaration
- Placing <T> inside curly braces
class Box<T>(val value: T) {
fun getValue(): T = value
}
fun main() {
val intBox = Box(123)
val strBox = Box("Hello")
println(intBox.getValue())
println(strBox.getValue())
}Solution
Step 1: Understand generic class usage
The classBoxholds a value of any type and returns it viagetValue().Step 2: Trace the main function
Two instances are created: one with an integer 123 and one with a string "Hello". CallinggetValue()returns these values.Final Answer:
123 Hello -> Option AQuick Check:
Generic class returns stored value [OK]
- Expecting object reference output instead of value
- Confusing type inference causing errors
- Assuming null is returned
class Container<T> {
var item: T
constructor(item: T) {
this.item = item
}
}Solution
Step 1: Check property initialization
The propertyitemis declared but not initialized and not marked as abstract or lateinit.Step 2: Understand Kotlin property rules
In Kotlin, non-null properties must be initialized or declared abstract/lateinit. Here,itemis neither initialized nor marked, causing a compile error.Final Answer:
Property 'item' must be initialized or be abstract -> Option DQuick Check:
Uninitialized property causes error [OK]
- Forgetting to initialize properties
- Misunderstanding constructor syntax
- Thinking generic declaration is wrong
PairBox that holds two values of possibly different types. Which is the correct declaration for this class in Kotlin?Solution
Step 1: Understand requirement for two different types
The class should accept two generic types, so it needs two type parameters, e.g.,TandU.Step 2: Check each option
class PairBox(val first: T, val second: U) correctly declares two generic types and constructor parameters. class PairBox<T>(val first: T, val second: T) uses one type for both values, not allowing different types. class PairBox { val first: T; val second: T } has wrong property types (second is T, should be U). class PairBox(val first: Any, val second: Any) usesAnywhich is not generic.Final Answer:
class PairBox<T, U>(val first: T, val second: U) -> Option AQuick Check:
Two generics for two types [OK]
- Using one generic type for both values
- Confusing property types in class body
- Using Any instead of generics
Ready to prove it?
Pass the test and this pattern moves unknown
