Enumeration types

An enumeration type is a set of named atomic enumeration values that are distinct from other values. You define the type using define-enum, and you reference enumeration values using colon notation:

(define-enum colors (red blue green))
(define favorite-color colors:green)

Displaying an enum just prints the enum name, but readable output using write (or the ~s format specifier) prepends the type name:

(format "~a" favorite-color) ⇒ "green"
(format "~s" favorite-color) ⇒ "colors:green"

The static values method returns a Java array of the enumeration values, in declaration order, while ordinal yields the index of an enumeration value:

(colors:values) ⇒ [red blue green]
((colors:values) 1) ⇒ blue
(favorite-color:ordinal) ⇒ 2

If you invoke the enumeration type as a function, it will map the name (as a string) to the corresponding value. (This uses the valueOf method.)

(colors "red") ⇒ red
(colors "RED") ⇒ throws IllegalArgumentException
(eq? favorite-color (colors:valueOf "green")) ⇒ #t

Kawa enumerations are based on Java enumerations. Thus the above is similar to a Java5 enum declaration, and the type colors above extends java.lang.Enum.

Syntax: define-enum enum-type-name option-pair... (enum-value-name ...) field-or-method-decl...

This declares a new enumeration type enum-type-name, whose enumerations values are the enum-value-name list. You can specify extra options and members using option-pair and field-or-method-decl, which are as in define-simple-class. (The define-enum syntax is similar to a define-simple-class that extends java.lang.Enum.)

(Note that R6RS has a separate Enumerations library (rnrs enum). Unfortunately, this is not compatible with standard Java enums. R6RS enums are simple symbols, which means you cannot distinguish two enum values from different enumeration types if they have the same value, nor from a vanilla symbol. That makes them less useful.)