Enum with properties and methods in Kotlin - Time & Space Complexity
Enums with properties and methods let us group related values with extra details and actions.
We want to see how the time to run code with enums changes as we use more enum values or call their methods.
Analyze the time complexity of the following code snippet.
enum class Color(val rgb: Int) {
RED(0xFF0000) {
override fun printName() = println("Red")
},
GREEN(0x00FF00) {
override fun printName() = println("Green")
},
BLUE(0x0000FF) {
override fun printName() = println("Blue")
};
abstract fun printName()
}
fun printAllColors() {
for (color in Color.values()) {
color.printName()
}
}
This code defines an enum with three colors, each having a property and a method. Then it loops over all colors and calls their method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over all enum values with
Color.values()and callingprintName(). - How many times: Once for each enum constant (3 times here, but can be more if enum grows).
As the number of enum constants grows, the loop runs once per constant.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 calls to printName() |
| 10 | 10 calls to printName() |
| 100 | 100 calls to printName() |
Pattern observation: The work grows directly with the number of enum values. More values mean more method calls.
Time Complexity: O(n)
This means the time to run the loop and call methods grows linearly with the number of enum constants.
[X] Wrong: "Enums are fixed and small, so their methods always run in constant time no matter what."
[OK] Correct: While enums often have few values, if you loop over all values or add many constants, the time grows with the number of constants, not always constant.
Understanding how enum methods run helps you explain how your code scales when using enums with many values or complex methods.
"What if the printName() method called another function that loops over a list inside each enum constant? How would the time complexity change?"