scala - 产量语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9796939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:00:53  来源:igfitidea点击:

scala - yield syntax

scalayield

提问by Void Main

I'm reading a book on scala programming (the Programming in Scala), and I've got a question about the yield syntax.

我正在阅读一本关于 Scala 编程的书(Scala 编程),我有一个关于 yield 语法的问题。

According to the book, the syntax for yield can be expressed like: for clauses yield body

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

but when I try to run the script below, the compiler complains about too many arguments for getName

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

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?
  }

so, my question is what is the "body" part of the yield syntax, how to use it?

所以,我的问题是 yield 语法的“主体”部分是什么,如何使用它?

回答by om-nom-nom

Shortly, any expression (even that that return Unit), but you must enclose that expression into the brackets or just drop them down (works only with a single statement expressions):

很快,任何表达式(即使是返回 Unit 的表达式),但您必须将该表达式括在括号中或将它们下拉(仅适用于单个语句表达式):

def scalaFiles = 
  for (
    file <- filesHere
    if file.isFile
    if file.getName.endsWith(".scala")
  ) yield {
    // here is expression
  }

code above will work (but with no sense):

上面的代码可以工作(但没有意义):

scalaFiles: Array[Unit]

Next option is:

下一个选项是:

for(...) yield file.getName

and as a tip, you can rewrite your for comprehension like that:

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

def scalaFiles = 
      for (
        file <- filesHere;
        if file.isFile;
        name = file.getName;
        if name.endsWith(".scala")
      ) yield {
        name
      }