Enum
Type
Enum is a type consisting of a set of named variants. They are appropriate when an input argument may take on one of several values.
The only valid assignment to something of enum type E
are immediate variants of E
.
Declaration
Enums are declared by the enum
keyword, followed by the name (starting with Uppercase), and the list of variants
between curly brackets {}
. All enum variants must be declared between these curly brackets in the same place where the
enum itself is declared.
enum Suit { Club, Diamond, Heart, Spade }
Different enums may have variants of the same name, but identically named variants of different enums are not interchangeable.
Enum variants
Enum variants are referred to using Enum.VariantName
, which represents an enum value.
var s: Suit = Suit.Club;
Enumeration of an enum's variants can be done using Enum.variants()
.
var variants: List<Suit> = Suit.variants();
Match statement/expression
To base logic off the value of an enum, the match
statement or expression is used. See the rules for match
in the
section about
match statement or expression.
function cardExplanationFull(suit: Suit) returns Text -> match(suit) {
Club -> "Club"
Diamond -> "Diamond"
Heart -> "Heart"
Spade -> "Spade"
}
Associating values or functions with enums
Enums in NPL cannot contain values or have methods/functions. To associate a value or behavior with an enum, use a function that operates on an enum value.
function valueOf(suit: Suit) returns Number -> match(suit) {
Club -> 10
else -> 0
}