Enumerations

# Enumerations

An enumeration (enum) is a type with a finite set of values, such as "yes", "no", "maybe", or "north", "south", "east", "west".

An enumeration is defined like this:

>>> enum class Answer { YES, NO, MAYBE }
>>> enum class Direction { NORTH, SOUTH, EAST, WEST }


Answer and Direction are the type names, the values of the types are written Answer.YES or Direction.SOUTH:

>>> var a: Answer = Answer.YES
>>> val b = Answer.NO
>>> val dir = Direction.EAST


Enum values have a nice toString method, one can also obtain their name as the name property:

>>> a
YES
>>> a.name
YES
>>> b
NO
>>> dir
EAST


Internally, however, enums are represented as integers. You can obtain the integer with the ordinal property. Enum values can be compared (with the order given by the declaration):

>>> a.ordinal
0
>>> b.ordinal
1
>>> dir.ordinal
2
>>> a < Answer.MAYBE
true
>>> dir < Direction.SOUTH
false


With the valueOf method of an enum class, one can convert a string to an enum value:

>>> Answer.valueOf("YES")
YES
>>> Direction.valueOf("WEST")
WEST
>>> Direction.valueOf("NOWHERE")
java.lang.IllegalArgumentException: No enum constant Line2.Direction.NOWHERE


One can also obtain a list of all possible values:

>>> for (e in Answer.values()) println(e)
YES
NO
MAYBE

 Enumerations