0
0
Kotlinprogramming~3 mins

Why enums constrain values in Kotlin - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if your program could automatically reject wrong answers without you writing endless checks?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
val day = readLine()
if(day == "Monday" || day == "Tuesday" || day == "Wednesday" /* and so on */) {
  // do something
}
After
enum class Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
val day = Day.valueOf(readLine()?.capitalize() ?: "Monday")
// do something with day
What It Enables

Enums let your program trust the data it works with, making it safer and easier to maintain.

Real Life Example

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.

Key Takeaways

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.