Dart中的收益示例 [英] yield example in Dart
问题描述
如何在Dart中像Scala一样使用yield?
Scala中有一个示例 https:/ /alvinalexander.com/scala/scala-for-loop-yield-examples-yield-tutorial
How to use yield in Dart as a same as Scala? There is an example in Scala "https://alvinalexander.com/scala/scala-for-loop-yield-examples-yield-tutorial"
scala> val a = Array(1, 2, 3, 4, 5)
a: Array[Int] = Array(1, 2, 3, 4, 5)
scala> for (e <- a if e > 2) yield e
res1: Array[Int] = Array(3, 4, 5)
如何在飞镖上做?
void main() {
var a = [1, 2, 3, 4, 5];
for (var e in a) {
if (e > 2) yield e;
}
}
推荐答案
for(e<-a,如果e> 2)的表达式e
表达式是 表达式 在Scala中。
评估为数组。 Dart没有将其作为直接表达式,但是您可以使函数以几乎相同的方式返回可迭代对象,然后立即调用它们以创建表达式:
The for (e <- a if e > 2) yield e
expression is an expression in Scala.
It evaluates to an array. Dart does not have that as a direct expression, but you can make functions that return iterables in much the same way, and then call them immediately to create an expression:
var a = [1, 2, 3, 4, 5]
var res = () sync* { for (var v in a) if (v > 2) yield v; } ();
在这里,我介绍一个函数()sync * {for(var v in a)如果(v> 2)产生v; }
并立即调用它。该函数返回 Iterable
。可迭代的元素是主体 yield
的值,在这种情况下为3、4和5。
Here I introduce a function () sync* { for (var v in a) if (v > 2) yield v; }
and calls it immediately. That function returns an Iterable
. The elements of that iterable are the values yield
'ed by the body, in this case 3, 4 and 5.
这篇关于Dart中的收益示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!