Last active
March 17, 2021 20:47
-
-
Save TimWhiting/e564a8c4daf7385c4949bd96ad533780 to your computer and use it in GitHub Desktop.
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
extension Nullable<T extends Object> on T? { | |
T unwrap([String message = '']) { | |
if (this == null){ | |
throw Exception('Null $T: $message'); | |
} else { | |
return this!; | |
} | |
} | |
T orDefault(T defaultValue) { | |
return this ?? defaultValue; | |
} | |
R when<R extends Object>(R Function(T) nonNull,{required R Function() orElse}){ | |
if (this == null){ | |
return orElse(); | |
} else { | |
return nonNull(this!); | |
} | |
} | |
} | |
void main() { | |
final String? hi = 'Hi'; | |
final String? none = null; | |
Greet(hi); | |
Greet(none); | |
final String name = none.orDefault('No name'); | |
print(name); | |
none.unwrap('No name'); | |
} | |
void Greet(String? greeting){ | |
print(greeting.when((s) => s + ' You!', orElse: () => 'Goodbye')); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment