为什么yield无法在scala中使用while循环

Rol*_*olt 4 scala yield-keyword

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

val ints: IndexedSeq[Int] = for(i <- 1 to 10) yield i
Run Code Online (Sandbox Code Playgroud)

但我发现yield无法使用while循环,例如:

while (resultSet.next()) yield new Row(resultSet)
Run Code Online (Sandbox Code Playgroud)

为什么Scala设计得像这样?

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

j-k*_*eck 6

因为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
}
Run Code Online (Sandbox Code Playgroud)

编译为(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
        ()
    }
  }
}
Run Code Online (Sandbox Code Playgroud)