Lambda syntax is white space sensitive?

I typically format my code putting { on a new line such as

while (true)
{

}

I found it surprising that this is a syntax error

args.forEach
{

}

While, of course, this syntax works

args.forEach {

}

Is this intentional in language design? or does it fall out of how the language is parsed?

It reminds me of JavaScript where

return
{
a:1,
b:2
}

does not work because optional semi-colons makes this statement ambiguous.

Yes, this is intentional. Kotlin doesn’t have semicolons, and a language without semicolons has to have semantic line breaks.

1 Like

Although is somewhat different in that, unlike the JS example, there’s only one possible/parseable interpretation of the code. It’s kinda unfortunate that formatting choices cause syntax errors. I’ll probably fall back to using

args.forEach(
{

})

to avoid mixing styles.

Regards

That’s not true. Your original code (with a line break after forEach) accesses the forEach property of the args object and then returns a no-argument lambda from the enclosing block. This code normally does not compile because no such property is defined, but it can be parsed perfectly well.

Both versions work. The first version works, too. But it has a different meaning than the second version.

The compiler cannot deduce the correct version, because both versions are correct syntactically.