0
0
Kotlinprogramming~15 mins

Enum with when exhaustive check in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Enum with when exhaustive check
📖 Scenario: You are building a simple traffic light controller. The traffic light can be RED, YELLOW, or GREEN.You want to write code that reacts to each light color and prints the correct action for drivers.
🎯 Goal: Create an enum class for the traffic light colors, then use a when expression with exhaustive checking to print the correct action for each color.
📋 What You'll Learn
Create an enum class called TrafficLight with values RED, YELLOW, and GREEN
Create a variable called currentLight and set it to TrafficLight.RED
Use a when expression with variable currentLight to print the correct action for each color
Ensure the when expression is exhaustive (no else branch)
Print the action string exactly as specified
💡 Why This Matters
🌍 Real World
Traffic lights are common in real life and controlling their behavior in software helps understand state management.
💼 Career
Enums and exhaustive when expressions are widely used in Kotlin development for clear and safe handling of fixed sets of options.
Progress0 / 4 steps
1
Create the enum class
Create an enum class called TrafficLight with these exact values: RED, YELLOW, and GREEN.
Kotlin
Need a hint?
An enum class groups related constants. Use enum class TrafficLight { RED, YELLOW, GREEN }.
2
Create the currentLight variable
Create a variable called currentLight and set it to TrafficLight.RED.
Kotlin
Need a hint?
Use val currentLight = TrafficLight.RED to set the current light.
3
Write the when expression
Write a when expression using the variable currentLight to assign a variable action a string describing what drivers should do for each light: "Stop" for RED, "Get Ready" for YELLOW, and "Go" for GREEN. Do not use an else branch.
Kotlin
Need a hint?
Use val action = when (currentLight) { TrafficLight.RED -> "Stop" ... } without an else branch.
4
Print the action
Write a print statement to display the value of the variable action.
Kotlin
Need a hint?
Use println(action) to show the action.