Multiple type parameters in Kotlin - Time & Space Complexity
When using multiple type parameters in Kotlin, we want to understand how the program's work grows as input sizes change.
We ask: how does the time needed change when the inputs for each type grow?
Analyze the time complexity of the following code snippet.
fun <A, B> pairElements(listA: List<A>, listB: List<B>): List<Pair<A, B>> {
val result = mutableListOf<Pair<A, B>>()
for (a in listA) {
for (b in listB) {
result.add(Pair(a, b))
}
}
return result
}
This function creates pairs from every element in listA with every element in listB.
- Primary operation: Nested loops over listA and listB.
- How many times: Outer loop runs once per element in listA; inner loop runs once per element in listB for each outer loop.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| listA = 10, listB = 10 | 100 |
| listA = 100, listB = 100 | 10,000 |
| listA = 1000, listB = 1000 | 1,000,000 |
Pattern observation: The total work grows by multiplying the sizes of both lists.
Time Complexity: O(n * m)
This means the time needed grows by multiplying the size of the first list (n) by the size of the second list (m).
[X] Wrong: "The time grows only with the size of one list because the other is just a type parameter."
[OK] Correct: Both lists have real sizes that affect the loops. The type parameters only name the types, but the loops run over actual elements, so both sizes matter.
Understanding how multiple inputs affect time helps you explain your code clearly and shows you can think about efficiency in real situations.
"What if we changed the inner loop to only run a fixed number of times regardless of listB's size? How would the time complexity change?"
Practice
<T, U> before its name?Solution
Step 1: Understand type parameters in Kotlin
Type parameters like <T, U> allow a function to accept multiple types, making it flexible.Step 2: Interpret the meaning of <T, U>
Having <T, U> means the function can work with two different types, T and U, independently.Final Answer:
The function uses two different type parameters, T and U, to work with multiple types. -> Option CQuick Check:
Multiple type parameters = flexible function types [OK]
- Thinking it limits to only one type at a time
- Assuming automatic type conversion happens
- Confusing type parameters with actual types
Solution
Step 1: Recall Kotlin generic function syntax
Type parameters are declared immediately after the fun keyword inside angle brackets, separated by commas.Step 2: Check each option's syntax
fun myFunction(param1: T, param2: U) {} correctly uses <T, U> after fun and before the function name, matching Kotlin syntax.Final Answer:
fun <T, U> myFunction(param1: T, param2: U) {} -> Option AQuick Check:
Type parameters go after fun with commas [OK]
- Missing comma between type parameters
- Placing type parameters after function name
- Putting type parameters after parameter list
fun <T, U> pairToString(pair: Pair<T, U>): String {
return "${pair.first} and ${pair.second}"
}
fun main() {
val result = pairToString(Pair(10, "cats"))
println(result)
}Solution
Step 1: Understand the function behavior
The function takes a Pair with types T and U, then returns a string combining first and second values.Step 2: Trace the main function call
pairToString is called with Pair(10, "cats"), so pair.first = 10 and pair.second = "cats".Final Answer:
10 and cats -> Option DQuick Check:
pair.first + " and " + pair.second = "10 and cats" [OK]
- Swapping first and second values
- Expecting Pair's default toString output
- Thinking it causes a compilation error
fun <T, U> combine(a: T, b: U): T {
return b
}Solution
Step 1: Check function return type and return statement
The function declares return type T but returns b which is of type U.Step 2: Understand type mismatch error
Returning U where T is expected causes a type mismatch compilation error.Final Answer:
Return type T does not match returned value b of type U. -> Option AQuick Check:
Return type must match returned value type [OK]
- Ignoring type mismatch between T and U
- Assuming Kotlin auto-converts types
- Missing comma in type parameters (not the case here)
Box that can hold two different types of items, T and U. Which of the following class declarations correctly uses multiple type parameters and allows storing and retrieving both items?Solution
Step 1: Check correct multiple type parameter declaration
class Box(val first: T, val second: U) { fun getFirst(): T = first fun getSecond(): U = second } declares class Box with <T, U> and constructor parameters of types T and U, which is correct.Step 2: Verify methods to retrieve both items
class Box(val first: T, val second: U) { fun getFirst(): T = first fun getSecond(): U = second } provides getFirst() returning T and getSecond() returning U, matching stored types.Final Answer:
class Box<T, U>(val first: T, val second: U) { fun getFirst(): T = first fun getSecond(): U = second } -> Option BQuick Check:
Multiple type parameters with matching properties and methods [OK]
- Using only one type parameter for both items
- Not declaring type parameters in class header
- Using undefined types without generics
Ready to prove it?
Pass the test and this pattern moves unknown
