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



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


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.


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



to avoid mixing styles.



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.


But why it works with parenthesis after lambda then? Can’t compiler deduce what it should be?

//Not working



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.