What if your fixed categories could carry their own secrets and actions, making your code smarter instantly?
Why Enum with properties and methods in Kotlin? - Purpose & Use Cases
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.
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.
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.
val red = "Red"; val redCode = "#FF0000"; fun printRed() { println("Color: $red, Code: $redCode") }
enum class Color(val code: String) { RED("#FF0000"); fun printInfo() { println("Color: $name, Code: $code") } }
You can create clear, organized sets of related constants that carry their own data and actions, making your programs smarter and easier to maintain.
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.
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.