4

I am a little confused by the various uses of the 'block' {...} contruct in scala especially when calling a higher order function like in the following example.

def higherOrder(func: Int => Int): Int = {
  func(4)
}

val f = ((x: Int) => x*x)

Then I can call higherOrder like so:

  1. higherOrder(f), or

  2. higherOrder {f}, or

  3. higherOrder { x => x*x }

(1) is obvious, but I can not wrap my head around how the syntax for (2) and (3) are parsed by the compiler Can somebody explain what (2) and (3) correspond to, with regard to the language specification?

Richard Sitze
  • 8,262
  • 3
  • 36
  • 48
Imaxd
  • 368
  • 2
  • 14
  • 2
    Duplicates http://stackoverflow.com/q/17160145/1296806 or http://stackoverflow.com/q/17639922/1296806 or http://stackoverflow.com/q/13872196/1296806 or whatever. Links to other dupes from those dupes. :) – som-snytt Aug 05 '13 at 00:19
  • Short answer: a param block can be just a block. A {block} evals to its last statement. – som-snytt Aug 05 '13 at 00:22
  • ok thanks for the pointers I think all those fancy syntaxes do more harm to the language than good. There should be one obvious way to do a given thing like in (the zen of) python – Imaxd Aug 05 '13 at 00:34

1 Answers1

4

See SLS 6.6 Function Applications. Function application is defined like this:

SimpleExpr ::= SimpleExpr1 ArgumentExprs
ArgumentExprs ::= ‘(’ [Exprs] ‘)’
                ...
                | [nl] BlockExpr

And BlockExpr is

BlockExpr ::= ‘{’ CaseClauses ‘}’
            | ‘{’ Block ‘}’

So after function or method name you could specify either arguments list in brackets or expression in braces.

senia
  • 37,745
  • 4
  • 88
  • 129