Enums
An enum defines a named set of constants, which is clearer than scattering magic numbers or strings through a program.
enum Direction North East South Westend
heading = Direction.Eastprintln heading # 1println heading == Direction.East # trueValues
Section titled “Values”Members are numbered from 0 in order. Give a member an explicit value with =; members after it continue counting from there.
enum Priority Low # 0 Medium # 1 High = 10 Critical # 11end
println Priority.Medium # 1println Priority.Critical # 11Values can be any type, such as strings:
enum Color Red = "#ff0000" Green = "#00ff00"end
println Color.Green # #00ff00A member is its value. Direction.East is the integer 1, so it compares, prints and serializes like one, and typeof(Direction.East) is integer.
Using enums
Section titled “Using enums”Enums work well with case:
enum Status Pending Active Closedend
fn label(status) case status when Status.Pending "waiting" when Status.Active "in progress" else "done" endend
println label(Status.Active) # in progressEnum methods
Section titled “Enum methods”| Method | Returns |
|---|---|
.size() | The number of members |
.keys() | The member names, in order |
.values() | The member values, in order |
.to_hashmap() | A hashmap of names to values |
.get(name, default) | The value of the member called name, or default |
enum HttpStatus OK = 200 NotFound = 404end
println HttpStatus.size() # 2println HttpStatus.keys() # ["OK", "NotFound"]println HttpStatus.to_hashmap() # {"OK": 200, "NotFound": 404}println HttpStatus.get("NotFound", 0) # 404println HttpStatus.get("Teapot", 418) # 418
for name in HttpStatus.keys() do println "${name} = ${HttpStatus.get(name, null)}"endWithout a default, looking up a missing name raises a ValueError:
enum HttpStatus OK = 200end
try HttpStatus.get("Teapot")catch e println e["message"] # Enum member 'Teapot' not found.end