9. Enumerations
Enumerations define a type whose values come from a fixed set of named cases. They are useful when you want to model a small closed set of states or options.
An enumeration is defined like:
enum State:
ON
OFF
end
And used as follows:
s1 := State.ON
s2 := State.OFF
assert(s1 != s2)
assert(s1 == State.ON)
Enumeration values are qualified with the enum name, so State.ON and State.OFF are distinct values of the type State.
Enums work naturally with control flow:
func is_on(s):
if s == State.ON:
return true
end
return false
end
When code needs to handle every possible enum value, use an exhaustive match. By default, every enum member must be handled exactly once, so adding a new member makes affected matches fail at compile time until they are updated.
func signal_name(s: State, r: Region) -> String:
match s:
case ON:
return "on"[r]
case OFF:
return "off"[r]
end
end
Enum cases are contextual: the matched expression determines their enum type.
An other: arm may be placed last to handle every member not covered by an explicit case. A match with other: does not need to be exhaustive. Use it when the remaining members need to share the same behavior.
match s:
case ON:
return "on"[r]
other:
return "off"[r]
end
Without other:, Jik continues to require every enum member to be matched explicitly.
Use enums when the possible values are known in advance and do not need to carry additional data. If each case needs associated values, variants are the more general construct.
A table can associate one stored value with every member of an enum.
---