Extensions on built-in types in Kotlin - Time & Space Complexity
When we add new functions to built-in types in Kotlin, it's important to see how fast these functions run.
We want to know how the time to run these extensions changes as the input size grows.
Analyze the time complexity of the following code snippet.
fun String.countVowels(): Int {
var count = 0
for (char in this) {
if (char.lowercaseChar() in "aeiou") {
count++
}
}
return count
}
val text = "Hello Kotlin Extensions"
println(text.countVowels())
This code adds a function to count vowels in any string by checking each character.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character in the string.
- How many times: Once for every character in the string (length of the string).
As the string gets longer, the function checks more characters one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character checks |
| 100 | About 100 character checks |
| 1000 | About 1000 character checks |
Pattern observation: The work grows directly with the string length; double the length, double the checks.
Time Complexity: O(n)
This means the time to count vowels grows in a straight line with the string size.
[X] Wrong: "Extensions always add extra time because they are special functions."
[OK] Correct: Extensions run like normal functions; their speed depends on what they do, not that they are extensions.
Understanding how your extension functions perform helps you write clean and efficient code, a skill valued in real projects and interviews.
"What if we changed the extension to count vowels only in the first half of the string? How would the time complexity change?"
Practice
Solution
Step 1: Understand extension functions concept
Extension functions allow adding new functions to existing types without changing their original code.Step 2: Compare options with concept
Only To add new functions to existing types without modifying their source code correctly describes this purpose. Options B and C talk about inheritance and overriding, which are different concepts. To convert one type to another automatically is unrelated.Final Answer:
To add new functions to existing types without modifying their source code -> Option BQuick Check:
Extension functions add new behavior without changing original code [OK]
- Confusing extension functions with inheritance
- Thinking extensions override existing methods
- Believing extensions convert types automatically
isEven for Int in Kotlin?Solution
Step 1: Recall extension function syntax
Extension functions are declared asfun TypeName.functionName(). Here,Int.isEven()is correct.Step 2: Check each option
fun Int.isEven(): Boolean { return this % 2 == 0 } matches the correct syntax. fun isEven(): Boolean { return this % 2 == 0 } misses the receiver type. fun Int.isEven: Boolean = this % 2 == 0 misses parentheses. fun isEven(Int): Boolean = Int % 2 == 0 has wrong parameter syntax.Final Answer:
fun Int.isEven(): Boolean { return this % 2 == 0 } -> Option AQuick Check:
Extension syntax = fun TypeName.functionName() [OK]
- Omitting the receiver type before function name
- Missing parentheses after function name
- Using parameter instead of receiver for extension
fun String.addExclamation() = this + "!"
fun main() {
val word = "Hello"
println(word.addExclamation())
}Solution
Step 1: Understand the extension function behavior
The extension functionaddExclamationadds an exclamation mark to the string.Step 2: Trace the main function output
Callingword.addExclamation()returns "Hello!" which is printed.Final Answer:
Hello! -> Option DQuick Check:
Extension adds "!" so output is "Hello!" [OK]
- Expecting original string unchanged
- Thinking extension adds multiple exclamations
- Assuming syntax error due to extension
fun Int.isPositive {
return this > 0
}Solution
Step 1: Check function declaration syntax
Extension functions must have parentheses after the function name, even if no parameters.Step 2: Identify the fix
Add parentheses:fun Int.isPositive(). Other options are incorrect because Boolean return is allowed, Int is valid receiver, and return statements are allowed.Final Answer:
Missing parentheses after function name; should be fun Int.isPositive() -> Option AQuick Check:
Extension functions need () after name [OK]
- Omitting parentheses after function name
- Thinking extensions can't return values
- Confusing receiver type validity
wordCount for String that returns the number of words separated by spaces. Which implementation correctly handles multiple spaces and empty strings?Solution
Step 1: Understand the problem requirements
We need to count words separated by spaces, ignoring extra spaces and empty strings.Step 2: Analyze each option
fun String.wordCount() = this.split(" ").size splits by space but counts empty strings if multiple spaces exist. fun String.wordCount() = this.trim().split(" ").filter { it.isNotEmpty() }.size trims, splits, filters out empty strings, then counts, correctly handling multiple spaces and empty strings. fun String.wordCount() = this.length returns string length, unrelated. fun String.wordCount() = this.count { it == ' ' } counts spaces, not words.Final Answer:
fun String.wordCount() = this.trim().split(" ").filter { it.isNotEmpty() }.size -> Option CQuick Check:
Trim, split, filter empty = correct word count [OK]
- Counting empty strings as words
- Using string length instead of word count
- Counting spaces instead of words
Ready to prove it?
Pass the test and this pattern moves unknown
