Why are {} needed in the following code in anonymous functions?

Early days with Scala learning. Why does using {} or using ( ) for parameters remove the error? Appreciate your help.


scala> x:Int => x + 1
:1: error: ‘;’ expected but ‘=>’ found.
x:Int => x + 1

scala> {x: Int => x + 1}
res0: Int => Int = $$Lambda$1013/325674467@53c6f96d

scala> (x: Int) => x + 1
res1: Int => Int = $$Lambda$1015/995482901@f3560d4

Hi Anoop,

the more interesting questing is: What do you want to do?

If you want to use a variable or value you should do:

var x = 10
val y = 20

The compiler knows the type, so you don’t have to write it (except it improves the readability of your code).

With your 2nd and 3rd try, you declare an anonymous function. With a name it would be like this:

def myFunc(x : Int) = {
  x + 1

You can use it for example in this way:

(0 to 10)
  .map( x => x + 1)

Have fun

Hi Chris,
Thank you. May be I am being slow here but I still do not see how using the block {} in 2nd try removes the compiler/interpreter error.


The syntax for anonymous functions require the parentheses surrounding the arguments, except when there is only one argument, and the function declaration occurs as a result of a block. So trying to omit parenthesis outside a block is just not Scala syntax :-).

@anoopsaxena, as per the documentation of the scala-lang.

In the case of a single untyped formal parameter, (x) => e can be abbreviated to x => e. If an anonymous function (x: T) => e with a single typed parameter appears as the result expression of a block, it can be abbreviated to x: T => e.

As an extra, I found some curious things on my research:
[0] - http://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala#L1389
[1] - https://issues.scala-lang.org/browse/SI-1565
[2] - https://issues.scala-lang.org/browse/SI-1564

1 Like

Hey Fabs,
Thank you for 2 things. First for pointing out an amazing resource to me and 2nd for the answer itself. That helped.


1 Like

I guess the error here because x:Int => x + 1 is ambiguity if no parenthesis. It can be parsed either as a function literal or as a type annotation x: (Int => +[x, 1]).

Note + is can be parsed as an infix type, and 1 can be parsed (with SIP-23) as a literal type.