0
0
Kotlinprogramming~3 mins

Why Enum with properties and methods in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your fixed categories could carry their own secrets and actions, making your code smarter instantly?

The Scenario

Imagine you have a list of fixed categories like days of the week or traffic light colors, and you want to store extra details for each, like a description or a number. Doing this manually means creating separate variables or classes for each item.

The Problem

Manually managing each category with its details is slow and messy. You might repeat code, forget to update all places, or mix data and behavior, making your program hard to read and error-prone.

The Solution

Using enums with properties and methods lets you group each fixed item with its own data and behavior neatly. This keeps your code clean, easy to update, and lets you treat each item as a smart object.

Before vs After
Before
val red = "Red"; val redCode = "#FF0000"; fun printRed() { println("Color: $red, Code: $redCode") }
After
enum class Color(val code: String) { RED("#FF0000"); fun printInfo() { println("Color: $name, Code: $code") } }
What It Enables

You can create clear, organized sets of related constants that carry their own data and actions, making your programs smarter and easier to maintain.

Real Life Example

Think of a traffic light system where each light (red, yellow, green) knows its color code and how long to stay on, all bundled in one place.

Key Takeaways

Enums group fixed items with their own data and functions.

This avoids repetitive code and keeps related info together.

It makes your code cleaner, safer, and easier to understand.