Visibility modifiers (public, private, internal, protected) in Kotlin - Time & Space Complexity
Let's explore how the use of visibility modifiers affects the time it takes for Kotlin code to run.
We want to see if changing visibility changes how long the program takes as it grows.
Analyze the time complexity of the following Kotlin class with different visibility modifiers.
class Example {
private val secretData = List(1000) { it * 2 }
fun getData(): List {
return secretData.filter { it % 3 == 0 }
}
}
This code creates a list and filters it using a public function, while the list itself is private.
Look for loops or repeated actions in the code.
- Primary operation: Filtering the list with
filterwhich checks each item. - How many times: Once per call, it checks all 1000 items in the list.
As the list size grows, the filtering takes longer because it looks at each item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the list size; double the list, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the size of the list being filtered.
[X] Wrong: "Making a variable private makes the code run faster."
[OK] Correct: Visibility controls who can use the code, not how fast it runs. The time depends on what the code does, not who can see it.
Understanding visibility modifiers helps you write clear and safe code. Knowing they don't affect speed shows you focus on what really matters when coding.
"What if the filter function was called multiple times instead of once? How would the time complexity change?"