0
0
Kotlinprogramming~5 mins

Visibility modifiers (public, private, internal, protected) in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Visibility modifiers (public, private, internal, protected)
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

Look for loops or repeated actions in the code.

  • Primary operation: Filtering the list with filter which checks each item.
  • How many times: Once per call, it checks all 1000 items in the list.
How Execution Grows With Input

As the list size grows, the filtering takes longer because it looks at each item.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The work grows directly with the list size; double the list, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the size of the list being filtered.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if the filter function was called multiple times instead of once? How would the time complexity change?"