Created
March 9, 2021 19:20
-
-
Save Mark-RSK/2a17e70b2ac8968262455b540d593479 to your computer and use it in GitHub Desktop.
Dart switch on type
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
class Cat { | |
String meow() => 'meow'; | |
} | |
String foo(dynamic a) { | |
switch (a.runtimeType) { | |
case String: | |
return 'str'; | |
case int: | |
return 'int'; | |
case Cat: | |
return a.meow(); | |
default: | |
return 'unknown'; | |
} | |
} | |
void main() { | |
print(foo('abc')); // 'str' ✅ | |
print(foo(42)); // 'int' ✅ | |
print(foo(Cat())); // 'meow' ✅ | |
// prints 'yes' ✅ | |
switch (Symbol("foo").toString()) { | |
case 'Symbol("foo")': | |
print("yes"); | |
break; | |
default: | |
print("no"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment