After reading What is the formal difference in Scala between braces and parentheses, and when should they be used?, I still don't know how to understand function value wrapped in {}
.
Consider the following two REPL sessions:
@ val f = { (x: Int) =>
x
val y = x
y
}
f: Int => Int = ammonite.$sess.cmd30$$$Lambda$1765/0x0000000801346840@24c7b944
@ { (x: Int) =>
x
val y = x
y
}
cmd31.sc:3: not found: value x
val y = x
^
Compilation Failed
I have several questions.
- Why the first snippet compiles while the second doesn't? In the first snippet, compiler knows the
{...}
as a whole is a function value. In the second snippet, only the(x: Int) => \n x
part is function value (Sorry about the\n
to indicate line break). Why? - Regarding the
{ (x: Int) => \n ... }
, when is it interpreted as function value and when is it not? - Is the curly brace (
{}
) part of the function value, or only(...) => ...
inside is function value? If it is a part it, does the form have a name? For example, I think(_ + _)
could be called function value's placeholder syntax.
Update: This is purely an Ammonite issue. See answer for detail.