关于scala:scala-yield语法

scala - yield syntax

我正在读一本有关Scala编程的书(《 Scala中的编程》),我对yield语法有疑问。

根据这本书,yield的语法可以表示为:
for子句的产生体

但是当我尝试运行以下脚本时,编译器会抱怨getName的参数过多

1
2
3
4
5
6
7
8
def scalaFiles =
  for (
    file <- filesHere
    if file.isFile
    if file.getName.endsWith(".scala")
  ) yield file.getName {
    // isn't this supposed to be the body part?
  }

因此,我的问题是yield语法的" body"部分是什么,如何使用它?


简短地说,任何表达式(即使是返回Unit的表达式),但您必须将该表达式括在方括号中或将其放下(仅适用于单个语句表达式):

1
2
3
4
5
6
7
8
def scalaFiles =
  for (
    file <- filesHere
    if file.isFile
    if file.getName.endsWith(".scala")
  ) yield {
    // here is expression
  }

上面的代码可以工作(但毫无意义):

1
scalaFiles: Array[Unit]

下一个选项是:

1
for(...) yield file.getName

作为提示,您可以这样重写您的理解力:

1
2
3
4
5
6
7
8
9
def scalaFiles =
      for (
        file <- filesHere;
        if file.isFile;
        name = file.getName;
        if name.endsWith(".scala")
      ) yield {
        name
      }