Extension properties in Kotlin - Time & Space Complexity
Extension properties in Kotlin let us add new properties to existing classes without changing them.
We want to see how the time to get these properties changes as input size grows.
Analyze the time complexity of the following code snippet.
val String.wordCount: Int
get() = this.split(" ").size
fun main() {
val sentence = "Kotlin extension properties are cool and useful"
println(sentence.wordCount)
}
This code adds a property to count words in a string by splitting it and counting parts.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Splitting the string into words using
split(" "). - How many times: The split method scans each character once, so it repeats roughly once per character in the string.
As the string gets longer, the split operation 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 number of characters in the string.
Time Complexity: O(n)
This means the time to get the extension property grows in a straight line with the string length.
[X] Wrong: "Getting an extension property is always instant and does not depend on input size."
[OK] Correct: Extension properties can run code like any function, so if they process data (like splitting a string), time depends on input size.
Understanding how extension properties work under the hood helps you explain performance clearly and shows you know Kotlin features well.
"What if the extension property cached the word count after the first call? How would the time complexity change on repeated calls?"