What if your program could automatically reject wrong answers without you writing endless checks?
Why enums constrain values in Kotlin - The Real Reasons
Imagine you are writing a program that handles days of the week. You ask users to type the day as text, like "Monday" or "Friday". But users might type "Mon", "monday", or even "Funday" by mistake.
Checking every possible typo or variation manually is slow and error-prone. You might forget some cases or accept invalid inputs, causing bugs or crashes later.
Enums let you define a fixed set of allowed values, like the seven days of the week. This way, the program only accepts valid days, preventing mistakes and making your code safer and easier to understand.
val day = readLine() if(day == "Monday" || day == "Tuesday" || day == "Wednesday" /* and so on */) { // do something }
enum class Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } val day = Day.valueOf(readLine()?.capitalize() ?: "Monday") // do something with day
Enums let your program trust the data it works with, making it safer and easier to maintain.
Think of a traffic light system where the light can only be Red, Yellow, or Green. Using enums ensures the program never accepts invalid colors like Blue or Purple.
Manual checks for allowed values are slow and error-prone.
Enums define a fixed set of valid options clearly and safely.
This reduces bugs and makes code easier to read and maintain.