为什么收益不能与scala中的while循环一起使用 [英] why yield can not work with while loop in scala
问题描述
在Scala中,yield
可以用于for循环;例如:
In Scala, yield
can work with for-loops; for example:
val ints: IndexedSeq[Int] = for(i <- 1 to 10) yield i
但是我发现yield
不能与while循环一起使用,例如像:
But I found that yield
can not work with while-loops, e.g. like:
while (resultSet.next()) yield new Row(resultSet)
Scala为什么如此设计?
Why is Scala designed like this?
我已经在Google和stackoverflow上进行了搜索,但是找不到答案.
I have searched on Google and stackoverflow, but could not find an answer.
推荐答案
因为while循环是java的while循环,因此'for循环'转换为以下函数的调用:<IndexedSeq>.map
(如果使用yield)或<IndexedSeq>.foreach
(如果您不关心结果).
Because a while loop is a java equivalent while loop, and the 'for loop' is translated to function call of: <IndexedSeq>.map
(if you use yield) or <IndexedSeq>.foreach
(if you don't care the result).
Scala代码示例:
Example Scala Code:
class ForVsWhileLoop {
val dummy = for(i <- 1 to 10) yield i
var dummy2 = Seq.empty[Int]
var i = 0
while(i <= 10)
dummy2 :+= i
}
编译为(scala -Xprint:parse ForVsWhileLoop.scala):
Compiles to (scala -Xprint:parse ForVsWhileLoop.scala):
[[syntax trees at end of parser]] // ForVsWhileLoop.scala
package <empty> {
class ForVsWhileLoop extends scala.AnyRef {
def <init>() = {
super.<init>();
()
};
// ***********************************************
// the 'for loop' is translated to a function call
val dummy = 1.to(10).map(((i) => i));
var dummy2 = Seq.empty[Int];
var i = 0;
// *******************
// classic while loop
while$1(){
if (i.$less$eq(10))
{
dummy2.$colon$plus$eq(i);
while$1()
}
else
()
}
}
}
这篇关于为什么收益不能与scala中的while循环一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!