[英]What does wrapping Scala lambda expressions in blocks (using both braces and parentheses) before executing them inline achieve?
While reading an article on monads I noticed that the author wrapped his lambdas in blocks using braces: 在阅读有关monads的文章时 ,我注意到作者使用括号将自己的lambda包装成块:
def foo(bar: String) = {
({ () => println(bar) })()
({ () => bar.length })()
}
How is that different than just using a single pair of parentheses? 这与仅使用一对括号有何不同? (Which does make sense syntactically.)
(这在语法上确实有意义。)
I tried both forms in the interpreter and they're both correct: 我在解释器中尝试了两种形式,它们都是正确的:
scala> ({ () => println(123) })()
123
scala> ( () => println(123) )()
123
My first guess was that it has something to do with scoping rules - but then again, lambdas don't have names so they shouldn't affect the namespace much. 我的第一个猜测是,它与作用域规则有关-但是,lambda并没有名称,因此它们不会对命名空间产生太大影响。
It does absolutely nothing. 它绝对不做任何事情。 The extra set of braces are ignored by the parser.
解析器将忽略多余的大括号。
Compile this code: 编译这段代码:
object Test {
def x = ({ () => println(123) })()
def y = ( () => println(123) )()
}
with -Xprint:parser
, and the intermediate result is: 使用
-Xprint:parser
,中间结果是:
[[syntax trees at end of parser]]
package <empty> {
object Test extends scala.AnyRef {
def <init>() = {
super.<init>();
()
};
def x = (() => println(123))();
def y = (() => println(123))()
}
}
x
and y
result in identical abstract syntax trees. x
和y
导致相同的抽象语法树。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.