gpt4 book ai didi

scala - 为什么 yield 不能在 Scala 中使用 while 循环

转载 作者:行者123 更新时间:2023-12-04 22:45:43 25 4
gpt4 key购买 nike

在 Scala 中,yield可以使用 for 循环;例如:

val ints: IndexedSeq[Int] = for(i <- 1 to 10) yield i

但我发现 yield不能使用 while 循环,例如喜欢:
while (resultSet.next()) yield new Row(resultSet)

为什么 Scala 是这样设计的?

我在 Google 和 stackoverflow 上搜索过,但找不到答案。

最佳答案

因为 while 循环是 java 等价的 while 循环,并且“for 循环”被转换为以下函数调用:<IndexedSeq>.map (如果您使用 yield)或 <IndexedSeq>.foreach (如果你不在乎结果)。

Scala 代码示例:

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):
[[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 - 为什么 yield 不能在 Scala 中使用 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27090229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com