Created
May 11, 2023 21:44
-
-
Save MelbourneDeveloper/68bfd14dd9f66473f382c5b732fae405 to your computer and use it in GitHub Desktop.
Pattern Matching Example
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 Animal { | |
String get name; | |
} | |
class Dog extends Animal { | |
@override | |
String get name => 'Spot'; | |
} | |
class Cat extends Animal { | |
@override | |
String get name => 'Garfield'; | |
} | |
void main() { | |
Animal pet = Dog(); | |
final sound = switch (pet) { | |
(Dog d) => '${d.name}: Woof!', | |
(Cat c) => '${c.name}: Meow!', | |
_ => '...', | |
}; | |
print(sound); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment