2

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.

4

2 回答 2

10

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.

于 2013-02-28T11:05:55.620 回答
6

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.

于 2013-02-28T11:02:52.040 回答