{a => statement1; statement2; } syntax


#1

I was recently introduced to the curly brace function syntax eg:

(1 to 3).foreach{i => println(i); println(i + 10)}
1
11
2
12
3
13

Anything that gets rid of a brace pair is a great boon. I just wondered if it can ever create syntactic ambiguity.


#2

(1 to 3).foreach({i => println(i); println(1 + 10)}) ==
(1 to 3) foreach {i => println(i); println(1 + 10)}

this is called “infix notation”


#3

Before I would have written:

(1 to 3).foreach(i => { println(i); println(i + 10) } )

or

(1 to 3).foreach(i => {
println(i)
println(i + 10)
} )

What’s particular nice is combining it with the case syntax I only discovered / rediscovered recently:

case class AAA(x: Int, y:Int)
val sp = (1 to 4) map (i => AAA(i, i + 10))
sp.foreach{case AAA(x, y) => println(x); println(y + 100) }
1
111
2
112
3
113
4
114


#4

Note that if you want to specify the parameter type, and/or the number of
parameters is not 1, you need parentheses around the part before the arrow;
otherwise they’re optional.


#5

There is no ambiguity.

First, a function can either take some args like f(x,y,z) or a single block expression like f { z }.

The beauty of the second syntax is when f takes a by-name arg, like Future { body }.

An old SO post.


#6

That is called infix, but you can write x.f(y) or x.f{y} or x f y or x f { y }. Brace syntax and infix syntax are not related.


#7

Thanks to lightweight method call syntax, you can do:

scala> 1 to 3 foreach println
1
2
3

#8

I very much appreciate that in Scala, I can write x+yz*, instead of
x.+(y.(z))*. Apart from that, I like the dots, parentheses and braces.

I find this more obvious and therefore easier to read:

(1 to 3).foreach { println }

than this

1 to 3 foreach println

Best, Oliver


#9

Fully agreed. The only codebase that does this consistently that I know of is scala/scala - and it still is a significant speed bump in reading the code for me, especially since there is plenty of other stuff going on there.