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.

2
  • 4
    I would say stackoverflow is such resource (scroll down) Commented Feb 28, 2013 at 10:47
  • Wow thanks, didn't know it existed :) Commented Feb 28, 2013 at 10:48

2 Answers 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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

TLDR: in this particular case there is no difference at all
In this case. But invokeFunc({ println("heeeey!"); () => "this is a string" }) would also work, proving the difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.