Enums & When Expression
Enums are fundamental for representing a fixed set of states or identifiers. In Autolang, Enums can define their own methods and pair powerfully with the when expression.
Defining an Enum and Methods
Just like classes, enums can declare methods. Using the when expression inside an enum method allows for highly readable, state-based dispatching. Note that you have to cover all branches or provide an else branch.
enum TrafficLight {
RED, YELLOW, GREEN;
// Enums can have methods. Using single-expression syntax here.
func getAction(): String = when (this) {
RED -> "Stop!"
YELLOW -> "Slow down!"
GREEN -> "Go!"
else -> "Unknown state"
}
}
val currentLight = TrafficLight.GREEN
println("The light is GREEN. What should I do?")
println(currentLight.getAction())
// Equality checks work seamlessly
val isSafe = currentLight == TrafficLight.GREEN
println("Is it safe to go? ${if (isSafe) "Yes" else "No"}")The when Expression
The when expression replaces traditional switch statements. It is safer (no fall-through, meaning no break needed) and highly concise. It can be used to match a specific value, or without an argument as a clean alternative to long if-else if chains.
// 1. Matching against a specific value
func getDayName(dayIndex: Int): String = when (dayIndex) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
else -> "Weekend or Invalid" // 'else' is required to be exhaustive
}
println("Day 3 is: ${getDayName(3)}")
// 2. Using 'when' without an argument (evaluates boolean expressions)
func evaluateScore(score: Int): String = when {
score >= 90 -> "Excellent"
score >= 80 -> "Great"
score >= 50 -> "Passed"
else -> "Failed"
}
println("Score 85 means: ${evaluateScore(85)}")