Skip to content

Instantly share code, notes, and snippets.

@TimWhiting
Last active March 17, 2021 20:47
Show Gist options
  • Save TimWhiting/e564a8c4daf7385c4949bd96ad533780 to your computer and use it in GitHub Desktop.
Save TimWhiting/e564a8c4daf7385c4949bd96ad533780 to your computer and use it in GitHub Desktop.
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