Enumerated types
通常enumerations,あるいはenumと表現される列挙型(Enumerated types)は、特別な種類のクラスです。決まった数の定数値の集まりを表現する型です。
Using enums
enumキーワードを用いて列挙型(enumerated type)を宣言します。
enum Color { red, green, blue }
列挙型のそれぞれの値はゲッターindexを持っています。
ゲッターindexは宣言された列挙型のゼロベースのポジションを返します。例えば、最初の列挙型の値の持つindexは0です。その次の列挙型の値の持つindexは1です。
assert(Color.red.index == 0); assert(Color.green.index == 1); assert(Color.blue.index == 2);
列挙型の全ての値を要素として持つリストを取得したい場合、列挙型の定数valuesを使います。
List<Color> colors = Color.values; assert(colors[2] == Color.blue);
列挙型の代表的な使用例としてはswitch文があります。switch文の中で、全ての列挙型の値を使用しないと警告が出ます。
var aColor = Color.blue; switch (aColor) { case Color.red: print('Red as roses!'); break; case Color.green: print('Green as grass!'); break; default: // Without this, you see a WARNING. print(aColor); // 'Color.blue' }
列挙型には下記の制限があります。
- 列挙型(enum)のサブクラスは作れない、列挙型に実装やミックスインはできない。
- 列挙型(enum)のインスタンスを生成することはできない。
関連情報:Dart language specification.
参考
https://dart.dev/guides/language/language-tour#enumerated-types