0
0
Kotlinprogramming~5 mins

Custom getters and setters in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom getters and setters
O(1)
Understanding Time Complexity

When using custom getters and setters in Kotlin, it's important to know how often these methods run as your program works.

We want to find out how the time to run changes when we access or change properties with custom code.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Rectangle(var width: Int, var height: Int) {
    var area: Int = 0
        get() = width * height
        set(value) {
            field = value
            width = value / height
        }
}

fun main() {
    val rect = Rectangle(10, 5)
    println(rect.area)
    rect.area = 50
    println(rect.width)
}

This code defines a rectangle with custom getter and setter for the area property.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The getter multiplies width and height each time area is accessed.
  • How many times: Once per access; no loops or recursion involved.
How Execution Grows With Input

Each time you get or set the area, the operations run once, no matter the size of width or height.

Input Size (n)Approx. Operations
101 multiplication or division
1001 multiplication or division
10001 multiplication or division

Pattern observation: The number of operations stays the same regardless of input size.

Final Time Complexity

Time Complexity: O(1)

This means accessing or setting the property takes the same short time no matter the values involved.

Common Mistake

[X] Wrong: "Custom getters and setters slow down the program a lot as values get bigger."

[OK] Correct: The operations inside getters and setters run once per access, so their time does not grow with the size of the values.

Interview Connect

Understanding how custom getters and setters work helps you explain property access performance clearly and confidently in real projects.

Self-Check

"What if the getter computed the area by looping over a list of rectangles? How would the time complexity change?"