scala for with () vs {} 括号 vs 花括号

use*_*285 6 for-loop scala

我已经看到 for 循环,带有括号 () 和花括号 {} 的理解它们看起来非常相似。我一直以为它们是一样的,直到我写了这段代码:

版本 1:

def findChar(c: Char, levelVector: Vector[Vector[Char]]): Pos = {
    val positions =
      for {
        row_index <- 0 to levelVector.length - 1
        col_index <- 0 to levelVector(row_index).length - 1
        if (levelVector(row_index)(col_index) == c)
      } yield Pos(row_index, col_index)
    if (positions.length == 1) positions.head
    else throw new Exception(s"expected to find 1 match, but found ${positions.length} matches instead")
  }
Run Code Online (Sandbox Code Playgroud)

版本 2:

def findChar(c: Char, levelVector: Vector[Vector[Char]]): Pos = {
    val positions =
      for (
        row_index <- 0 to levelVector.length - 1;
        col_index <- 0 to levelVector(row_index).length - 1;
        if (levelVector(row_index)(col_index) == c)
      ) yield Pos(row_index, col_index)
    if (positions.length == 1) positions.head
    else throw new Exception(s"expected to find 1 match, but found ${positions.length} matches instead")
  }
Run Code Online (Sandbox Code Playgroud)

版本 1 有花括号,而版本 2 有括号。但我也注意到第 2 版没有在箭头线末尾使用分号就无法编译。为什么是这样?!这两个fors是一回事吗?

Ram*_*jan 4

不,它们不一样。

{}表示考虑next line(\n)对代码行进行分组

()也意味着分组,但不考虑下一行(\n),因此即使您位于中间,代码行\n内的所有代码也被视为一行。()