Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top