简体   繁体   中英

Does Dart have a comma operator?

Consider the following line of code that doesn't compile in Dart -- lack of comma operator, but comparable things are totally fine in JavaScript or C++:

final foo = (ArgumentError.checkNotNull(value), value) * 2;

The closest I could get with an ugly workaround is

final foo = last(ArgumentError.checkNotNull(value), value) * 2;

with function

T last<T>(void op, T ret) => ret;

Is there a better solution?

Dart does not have a comma operator similar to the one in JavaScript.

There is no obviously better solution than what you already have.

The work-around operation you introduced is how I would solve it. I usually call it seq for "sequence" if I write it.

There is sadly no good way to use an extension operator because you need to be generic on the second operand and operators cannot be generic. You could use an extension method like:

extension Seq on void {
  T seq<T>(T next) => next;
}

Then you can write ArgumentError.checkNotNull(value).seq(value) .

(For what it's worth, the ArgumentError.checkNotNull function has been changed to return its value, but that change was made after releasing Dart 2.7, so it will only be available in the next release after that).

If the overhead doesn't matter, you can use closures without arguments for a similar effect (and also more complex operations than just a sequence of expressions).

final foo = () {
  ArgumentError.checkNotNull(value);
  return value;
} ();

This is not great for hot paths due to the overhead incurred by creating and calling a closure, but can work reasonably well outside those.

If you need this kind of test-plus-initialization pattern more than once, the cleanest way would arguably be to put it in a function of its own, anyway.

T ensureNotNull<T>(T value) {
  ArgumentError.checkNotNull(value);
  return value;
}

final foo = ensureNotNull(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM