0
0
Kotlinprogramming~5 mins

Interface with default implementations in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Interface with default implementations
O(n)
Understanding Time Complexity

We want to understand how the time needed to run code changes when using interfaces with default implementations in Kotlin.

Specifically, how does calling default methods affect the work done as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

interface Printer {
    fun printAll(items: List) {
        for (item in items) {
            print(item)
        }
    }
}

class ConsolePrinter : Printer

fun main() {
    val printer = ConsolePrinter()
    val data = List(5) { "Hello" }
    printer.printAll(data)
}

This code defines an interface with a default method that prints all items in a list, then uses it in a class.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop inside the default method printAll that goes through each item in the list.
  • How many times: It runs once for every item in the input list.
How Execution Grows With Input

As the list size grows, the number of print operations grows the same way.

Input Size (n)Approx. Operations
1010 print calls
100100 print calls
10001000 print calls

Pattern observation: The work grows directly with the number of items; doubling items doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the method grows in a straight line with the number of items to print.

Common Mistake

[X] Wrong: "Using default methods in interfaces makes the code run faster or slower by itself."

[OK] Correct: The default method is just code that runs like any other function; its speed depends on what it does, not where it is defined.

Interview Connect

Understanding how default interface methods work helps you explain code design choices and their impact on performance clearly and confidently.

Self-Check

"What if the default method called another method that itself loops over the list? How would the time complexity change?"