我正在读一本关于scala编程(Scala中的编程)的书,我有一个关于yield语法的问题。
根据这本书,yield的语法可以表达为: for子句yield
但是,当我尝试运行下面的脚本时,编译器报告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?
}那么,我的问题是什么是what语法的"body“部分,如何使用它?
发布于 2012-03-21 08:30:00
简而言之,任何表达式(即使是返回Unit),但您必须将该表达式括在括号中或直接将其下拉(仅适用于单个语句表达式):
def scalaFiles =
for (
file <- filesHere
if file.isFile
if file.getName.endsWith(".scala")
) yield {
// here is expression
}上面的代码可以工作(但没有意义):
scalaFiles: Array[Unit]下一个选项是:
for(...) yield file.getName作为一个提示,你可以像这样重写你的理解:
def scalaFiles =
for (
file <- filesHere;
if file.isFile;
name = file.getName;
if name.endsWith(".scala")
) yield {
name
}https://stackoverflow.com/questions/9796939
复制相似问题