Lambda syntax is white space sensitive?


#1

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.


#2

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


#3

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


#4

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.


#5

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

//Not working
list.forEach 
{
  println(it)
}

//Working
list.forEach()
{
  println(it)
}

#6

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.