我总是想知道为什么有时使用函数文字我们可以忽略大括号,即使是多个语句.为了说明这一点,多行函数文字的语法是用大括号括起语句.像这样,
val fl = (x: Int) => {
println("Add 25 to "+x)
x + 25
}
Run Code Online (Sandbox Code Playgroud)
但是,当您将其传递给单参数函数时,您可以忽略函数文字所需的大括号.
所以对于给定的函数f,
def f( fl: Int => Int ) {
println("Result is "+ fl(5))
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样调用f(),
f( x=> {
println("Add 25 to "+x)
x + 25
})
-------------------------
Add 25 to 5
Result: 30
Run Code Online (Sandbox Code Playgroud)
或者在函数调用中使用花括号而不是括号时,可以从函数文本中删除内部花括号.所以下面的代码也可以,
f{ x=>
println("Add 25 to "+x)
x + 25
}
Run Code Online (Sandbox Code Playgroud)
上面的代码更具可读性,我注意到很多例子都使用这种语法.但是,是否有任何我可能错过的特殊规则,以解释为什么这样做符合预期?