简体   繁体   中英

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:

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.

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:

[[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM