Curly braces and lambdas

This compiles
fun foo(): Int {
return if(true) {2} else 3
but this doesn’t
fun bar(x: Int): Int {
return {2}
Same problem here
fun foo1(): Int = 2
fun bar1(): Int = {2}
The curly braces around “2” are interpreted as scope delimiters in foo, but as a lambda function in bar.
How is this ambiguity resolved and what is the rationale that {term} may be interpreted as a lambda function, even if there is no “it” or a parameter followed by “->”?

I believe that { after an if is always taken as the body of the if.
return doesn’t have a body so it can’t be anything else.

Likewise in your last example fun bar1(): Int = {2} is a function with an expression body, hence { is interpreted as the beginning of a lambda.

Note that lambdas don’t have to name inputs (or even have them).

1 Like