在括号()和大括号{}中传递参数给函数之间的形式区别是什么?
我从《Scala编程》这本书中得到的感觉是,Scala非常灵活,我应该使用我最喜欢的那一种,但我发现有些情况可以编译,而其他情况则不行。
例如(只是作为一个例子;我很感激任何讨论一般情况的回复,而不仅仅是这个特定的例子):
val tupleList = List[(String, String)]()
val filtered = tupleList.takeWhile( case (s1, s2) => s1 == s2 )
=>错误:简单表达式的非法开始
val filtered = tupleList.takeWhile{ case (s1, s2) => s1 == s2 }
= >好。
社区正在努力标准化大括号和圆括号的使用,参见Scala风格指南(第21页):http://www.codecommit.com/scala-style-guide.pdf
对于高阶方法调用,推荐的语法是总是使用大括号,并跳过点:
val filtered = tupleList takeWhile { case (s1, s2) => s1 == s2 }
对于“普通”方法调用,应该使用点和圆括号。
val result = myInstance.foo(5, "Hello")
There are a couple of different rules and inferences going on here: first of all, Scala infers the braces when a parameter is a function, e.g. in list.map(_ * 2) the braces are inferred, it's just a shorter form of list.map({_ * 2}). Secondly, Scala allows you to skip the parentheses on the last parameter list, if that parameter list has one parameter and it is a function, so list.foldLeft(0)(_ + _) can be written as list.foldLeft(0) { _ + _ } (or list.foldLeft(0)({_ + _}) if you want to be extra explicit).
但是,如果添加case,就会得到一个部分函数,而不是其他函数,Scala不会推断部分函数的花括号,所以list。Map (case x => x * 2)将不起作用,但两者都列出。映射({case x => 2 * 2})和列表。映射{case x => x * 2}将。