Dart supports "if null" access and assignment operators — ??, ??=.
Equivalent "if not null" operators would also be useful, particularly when non-nullable types land (https://github.com/dart-lang/language/issues/110). They would allow concise use of nullable variables in a similar manner to quiver's Optional. E.g., instead of:
Optional<Foo> foo;
foo = foo.transform(changeFoo);
final bar = foo.transform(fooToBar);
nullable variables could be used:
Foo? foo;
foo ?!= changeFoo(foo);
final bar = foo ?! fooToBar(foo);
It is a common pattern to "do something if something is not null". The ?. operation allows calling methods on an object if it is not null, but there is no similar feature to guard a general operation by something being not-null (the opposite of ??).
The ?! operator is probably not viable (the sequence can occur naturally, e.g., x ?! b : c).
Good point, !? and !?= should be a more viable alternative and more memorable since it matches the structure of the long-form equivalent: x ! /*= null*/ ? b /*: null*/
Something like that:
border: borderColor ?? Border.all(color: borderColor, width: 1),
border is optional, so I have to do:
border: borderColor != null
? Border.all(color: borderColor, width: 1)
: null,
border: borderColor !? Border.all(color: borderColor, width: 1),
If anonymous methods (#260) are implemented, you would be able to write it as
border: borderColor?.{return Border.all(color: this, width: 1);}
or even something like this:
border: borderColor?.{-> Border.all(color: this, width: 1)}
This doesn't require adding any new operators b/c expr?.method already conveys the meaning of "if expr is not null, return the result of the method, or else return null".
NOTE: It seems we have two concurrent proposals competing for the symbol -> (#260 and #762). Maybe we can find a way to reconcile them?
Probably not very compatible with Dart explicit bool rules, but another option would be to allow an exception with null and use the && short-circuit operator like in C-like languages: border: borderColor && Border.all(color: boderColor, width: 1).
Most helpful comment
Good point,
!?and!?=should be a more viable alternative and more memorable since it matches the structure of the long-form equivalent:x ! /*= null*/ ? b /*: null*/