简体   繁体   中英

Scala anonymous function syntax

I am a scala newbie.

What is the difference between

 invokeFunc(() => { "this is a string" } )

and

 invokeFunc({ () => "this is a string" })

If you have a good resource for small scala nuances I would appreciate it.

TL;DR : those two code snippets are equivalent.

In () => { "this is a string" } the curly brackets introduce a block of code. As this block of code contains only one expression, it is essentially useless and you could just have written () => "this is a string" .

Also, scala will almost always let you choose whether you use parentheses or curly brackets when calling a method. So println("hello") is the same as println{"hello"} . The reason scala allows curly bracket is so that you can define methods that you can use like it was a built-in part of the language. By example you can define:

def fromOneToTen( f: Int => Unit ) { 
  for ( i <- 1 to 10 ) f(i) 
}

and then do:

fromOneToTen{ i => println(i) }

The curly braces here make it look more like a control structure such as scala's built-in while .

So invokeFunc(() => { "this is a string" } ) is the same as invokeFunc{() => { "this is a string" } }

As a last point, parentheses can always be used anywhere around a single expression, so (5) is the same as 5 . And curly braces can always be used to define a block containing a series of expressions, the block returning the last expression. A special case of this is a block of a single expression, in which case curly braces play the same role as parentheses. All this means that you can always add superfluous parentheses or curly brackets around an expression. So the following are all equivalent: 123 , {123} , (123) , ({123}) and so on.

Which also means that:

invokeFunc(() => "this is a string")

is the same as

invokeFunc({ () => "this is a string" })

which is the same as

invokeFunc({( () => "this is a string" )})

and so on.

To my understanding, the first has an anonymous function, while the second has a block. However, the last element of a block returns in Scala, and so the block returns the same anonymous function, which then becomes the parameter of the method.

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