多行函数文字作为 Scala 中的参数 [英] Multiline function literal as arguments in Scala

查看:33
本文介绍了多行函数文字作为 Scala 中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道为什么有时使用函数文字我们甚至可以忽略多个语句的大括号.为了说明这一点,多行函数文字的语法是用大括号将语句括起来.像这样,

I always wondered why sometimes with function literals we can ignore the curly brace even for multiple statements. To illustrate this, the syntax for a multiline function literal is to enclose the statements with curly braces. Like so,

val fl = (x: Int) => {
  println("Add 25 to "+x)
  x + 25
}

但是,当您将其传递给单参数函数时,您可以忽略函数字面量所需的花括号.

However, when you pass it to a single-argument function, you can ignore the required curly brace for the function literal.

所以对于给定的函数 f,

So for a given function f,

def f( fl: Int => Int ) {
  println("Result is "+ fl(5))
}

你可以这样调用 f(),

You can call f() like this,

f( x=> {
  println("Add 25 to "+x)
  x + 25
})
-------------------------
Add 25 to 5
Result: 30

或者当你在函数调用中使用大括号代替括号时,你可以从函数字面量中移除内部的大括号.所以下面的代码也可以工作,

Or when you use curly braces instead of parenthesis in the function call, you can remove the inner curly braces from the function literal. So the following code will also work,

f{ x=>
  println("Add 25 to "+x)
  x + 25
}

上面的代码更具可读性,我注意到很多示例都使用这种语法.但是,是否有任何我可能遗漏的特殊规则来解释为什么按预期工作?

The above code is more readable and I notice that a lot of examples use this syntax. However, is there any special rule that I may have missed, to explain why this is working as intended?

推荐答案

只有几个简单的语法规则.规范的附录值得细读.

There are just a couple of simple syntax rules. The appendix of the spec is worth perusing.

函数文字或匿名函数 (6.23) 看起来像 x =>;Exprx =>块 分别取决于上下文是 Expr 还是 ResultExpr.

A function literal or anonymous function (6.23) will look like x => Expr or x => Block depending on whether the context is an Expr or a ResultExpr, respectively.

函数应用程序 (6.6) 看起来像 f(Expr, Expr)f BlockExpr,即 f{ Block }.也就是说,一个 BlockExpr 只是 {...} 中的一个块语句序列.

A function application (6.6) will look like f(Expr, Expr) or f BlockExpr, i.e., f{ Block }. That is, a BlockExpr is just a sequence of block statements inside {...}.

当你调用 f(g) 时,g 是一个 Expr,所以作为函数文字,x =>表达式.Expr 可以是 BlockExpr,x =>;{ ... }.

When you call f(g), then g is an Expr, so as a function literal, x => Expr. The Expr can be a BlockExpr, x => { ... }.

当你调用 f{ Block } 时,然后 f { x =>... } 在块的 ResultExpr 中有函数文字(它只是一个语句序列,不需要大括号).

When you call f{ Block }, then f { x => ... } has the function literal in ResultExpr of a Block (which is just a sequence of statements, no braces required).

在这里,很明显 anon func 位于块的底部:

Here, it's obvious that the anon func is at the bottom of a block:

scala> def m(x: Int=>Int) = x(5)
m: (x: Int => Int)Int

scala> m {
     | val y = 7
     | x => // no brace
     | x+y+1
     | }
res0: Int = 13

这篇关于多行函数文字作为 Scala 中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆