Skip to content

Instantly share code, notes, and snippets.

@RyosukeOK
Last active January 13, 2023 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyosukeOK/061d3b5eb903d1ad09466b44c1ce0849 to your computer and use it in GitHub Desktop.
Save RyosukeOK/061d3b5eb903d1ad09466b44c1ce0849 to your computer and use it in GitHub Desktop.
区分オブジェクト(enum版)
void main() {
// e.g. 画面のドロップダウンリストで選択された区分名から対応する区分オブジェクトを探す
final selectedFeeTypeName = 'adult';
final fee = Fee.values.byName(selectedFeeTypeName);
print(fee);
assert(fee.yen.value == Yen(100).value);
assert(Fee.adult.compareTo(Fee.child) == 50);
final charge = Charge(fee);
charge.yen();
}
/// 円の値オブジェクト
class Yen {
const Yen(this.value);
final int value;
}
class Charge {
const Charge(this.fee);
// interfaceを使っていない
final Fee fee;
void yen() {
print(fee.yen.value);
}
}
/// enhanced enums
enum Fee implements Comparable<Fee> {
adult(yen: Yen(100), label: '大人'),
child(yen: Yen(50), label: '子供'),
senior(yen: Yen(80), label: 'シニア'),
;
const Fee({
required this.yen,
required this.label,
});
@override
final Yen yen;
@override
final String label;
@override
int compareTo(Fee other) => yen.value - other.yen.value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment