简体   繁体   English

Dart 有逗号运算符吗?

[英]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++:考虑以下在 Dart 中无法编译的代码行——缺少逗号运算符,但在 JavaScript 或 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. Dart 没有类似于 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.我通常把它叫做seq为“序列”如果我写它。

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) .然后你可以写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). (就其价值而言, ArgumentError.checkNotNull函数已更改为返回其值,但该更改是在 Dart 2.7 发布后进行的,因此它只会在此后的下一个版本中可用)。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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