Skip to content

Instantly share code, notes, and snippets.

@BenoitDuffez
Last active May 18, 2021 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenoitDuffez/e53713a8453b5aeb9b7972dc6d0c2d4c to your computer and use it in GitHub Desktop.
Save BenoitDuffez/e53713a8453b5aeb9b7972dc6d0c2d4c to your computer and use it in GitHub Desktop.
SO #67577995 let implementation
O let<I extends Object, O>(
I? value,
O Function(I) cb,
{O Function()? or}) {
if (value != null) {
return cb(value);
}
if (or != null) {
return or();
}
O? returnNull = null;
if (returnNull is O) {
return returnNull;
}
throw ArgumentError.value(null, "or",
"Please provide a default non-null value");
}
class A {
final int a = 42;
}
void test(A a, String name) {
print("$name=${a.a}");
}
void main() {
A? x;
let(x, (it) => test(it, "x"), or: () => print("x is null"));
A? y = A();
let(y, (it) => test(it, "y"), or: () => print("y is null"));
A? z = A();
let<A, void>(z, (it) => test(it, "z"), or: () => print("z is null"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment