Last active
May 18, 2021 20:51
-
-
Save BenoitDuffez/e53713a8453b5aeb9b7972dc6d0c2d4c to your computer and use it in GitHub Desktop.
SO #67577995 let implementation
This file contains 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
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