Created with <3 with dartpad.dev.
Last active
April 24, 2023 23:23
-
-
Save johnpryan/349650f3936c79363f81ee0f1d6e8a12 to your computer and use it in GitHub Desktop.
Patterns example
This file contains 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
class Drink { | |
int ounces; | |
Drink(this.ounces); | |
} | |
class Coffee extends Drink { | |
final bool decaf; | |
Coffee(int ounces, {this.decaf = false}) : super(ounces); | |
} | |
class SportsDrink extends Drink { | |
final String? flavor; | |
SportsDrink(int ounces, this.flavor) : super(ounces); | |
} | |
void main() { | |
var drinks = <Drink>[ | |
Coffee(12, decaf: true), | |
SportsDrink(16, null), | |
]; | |
for (var drink in drinks) { | |
switch(drink) { | |
case Coffee(:var decaf): | |
print('coffee (decaf: $decaf)'); | |
case SportsDrink(:final flavor?): | |
print('coffee (flavor: $flavor)'); | |
default: | |
print("no match"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment