0
0
Kotlinprogramming~5 mins

Why delegation avoids inheritance in Kotlin - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why delegation avoids inheritance
O(n)
Understanding Time Complexity

We want to see how using delegation instead of inheritance affects the time it takes for a program to run.

Specifically, how does the program's work grow when it uses delegation compared to inheritance?

Scenario Under Consideration

Analyze the time complexity of the following Kotlin code using delegation.


interface Printer {
    fun print()
}

class RealPrinter : Printer {
    override fun print() {
        println("Printing document")
    }
}

class DelegatingPrinter(private val printer: Printer) : Printer by printer

fun main() {
    val realPrinter = RealPrinter()
    val delegatingPrinter = DelegatingPrinter(realPrinter)
    delegatingPrinter.print()
}
    

This code shows a class using delegation to pass print calls to another class instead of inheriting from it.

Identify Repeating Operations

Look for repeated actions that affect time.

  • Primary operation: Calling the print() method through delegation.
  • How many times: Each call to print() is forwarded once to the real printer.
How Execution Grows With Input

Each print call goes through delegation once, so the work grows directly with how many times print() is called.

Input Size (n)Approx. Operations
1010 calls forwarded once each
100100 calls forwarded once each
10001000 calls forwarded once each

Pattern observation: The number of operations grows directly with the number of calls, no extra repeated work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of method calls, without extra overhead from delegation.

Common Mistake

[X] Wrong: "Delegation adds a lot of extra work compared to inheritance because it calls methods twice."

[OK] Correct: Delegation forwards calls directly once, so it does not double the work. It just passes the call along efficiently.

Interview Connect

Understanding how delegation affects time helps you explain design choices clearly and shows you know how code structure impacts performance.

Self-Check

"What if the delegated method called another delegated method inside? How would that affect the time complexity?"