-
Notifications
You must be signed in to change notification settings - Fork 209
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Non null coalescing operator #2165
Comments
Will conflict with |
Would |
We could do the following in current Dart: // An identity method on all non-null objects.
extension Id on Object {
X id<X>(X x) => x;
}
// Example
void main() {
var i = 1 as int?; // Obtain an expression whose type is nullable.
String? s = i?.id('Whatever');
// Compare: i == null ? null : 'Whatever';
} It's a bit verbose (using 6 chars,
|
@eernstg Not related to the issue, but to your last comment. You say that |
Yes, extension methods are resolved statically, and this means that the compiler knows exactly which snippet of code the invocation will execute, so we can soundly inline it (if the given function is simple enough, and this one is ;-). |
@hamishjohnson Taking inspiration from Kotlin scope functions, I usually solve this kind of problems this way, applied to your example: extension ScopeFunctions<T> on T {
/// Calls the specified function [block] with `this` value
/// as its argument and returns its result.
R let<R>(R Function(T) block) => block(this);
}
Future<UserClaims?> getClaims(User firebaseUser) async {
final idTokenResult = await firebaseUser.getIdTokenResult();
return idTokenResult.claims?.let(UserClaims.fromJson);
} |
Those are nice solutions, didn't think to try to solve it that way. |
There is a number of similar requests, the earliest probably #360, so I'll close this as a duplicate. |
I find myself having to write this type of code quite often when dealing with nullable values:
TypeX != null ? TypeY : null;
A quick example I found, in with firebase auth:
I thought it would be nice to have a non-null coalescing operator to deal with this type of scenario. So, opposed to the null coalescing operator, if it evaluates the item on the left to be null, it returns null. But if it evaluates the left side to be non-null, then it continues on and returns the right side. Perhaps it would look something like this:
TypeX !? TypeY
Or, with my example:
n.b.
?!
could also be the operator. For some reason, it looks better and feels nicer to type, though it's less clearThe text was updated successfully, but these errors were encountered: