Last active
September 1, 2020 10:04
-
-
Save haarts/5d7ab193c13e6f9f4ac42589cd95f894 to your computer and use it in GitHub Desktop.
safe money
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class Currency { | |
const Currency(this.precision, this.currencyCode); | |
final int precision; | |
final String currencyCode; | |
static List<Currency> all() { | |
return [Chf(), Xbt()]; | |
} | |
} | |
class Xbt extends Currency { | |
const Xbt() : super(8, 'XBT'); | |
} | |
class Chf extends Currency { | |
const Chf() : super(2, 'CHF'); | |
} | |
class Money<T extends Currency> { | |
Money(this.amount); | |
final int amount; | |
int get precision { | |
return _currency.precision; | |
} | |
String get currencyCode { | |
return _currency.currencyCode; | |
} | |
Currency get _currency => Currency.all().firstWhere((c) => c.runtimeType == T); | |
@override | |
String toString() => 'Money($amount, $currencyCode)'; | |
} | |
void main() { | |
var m1 = Money<Chf>(100); | |
print(m1); | |
print(m1.precision); | |
var m2 = Money<Xbt>(1); | |
print(m2); | |
print(m2.precision); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment