Enums
Enums represent a fixed set of distinct constant values. In Autolang, enums can declare methods and dispatch states cleanly with the when expression.
Declaring Enums & Methods
Declare enum constants separated by commas, terminated with a semicolon if methods are declared inside the enum. Inside an enum method, this refers to the active enum constant.
enum OrderStatus {
PENDING, PROCESSING, SHIPPED, DELIVERED, CANCELLED;
fun isTerminal(): Bool = when (this) {
DELIVERED -> true
CANCELLED -> true
else -> false
}
fun label(): String = when (this) {
PENDING -> "Order Pending"
PROCESSING -> "Processing Warehouse"
SHIPPED -> "In Transit"
DELIVERED -> "Delivered Successfully"
CANCELLED -> "Order Cancelled"
else -> "Unknown"
}
}
val currentStatus = OrderStatus.PROCESSING
println("Current label: " + currentStatus.label())
println("Is terminal state? " + currentStatus.isTerminal())Comparing Enum Values
Enum values are compared directly with == and !=. They can also be passed into functions or stored in collections.
enum OrderStatus {
PENDING, PROCESSING, SHIPPED, DELIVERED, CANCELLED;
}
val requiredState = OrderStatus.SHIPPED
val actualState = OrderStatus.SHIPPED
println("States match: " + (requiredState == actualState)) // true
println("Not pending: " + (requiredState != OrderStatus.PENDING)) // true
val allowedTransitions = [OrderStatus.PENDING, OrderStatus.PROCESSING]
if (OrderStatus.PENDING in allowedTransitions) {
println("Status eligible for modification")
}