5

In Scala, we can have:

println { "Hello, world!" }

And from the book 'Programming in Scala':

The purpose of this ability to substitute curly braces for parentheses for passing in one argument is to enable client programmers to write function literals between curly braces. This can make a method call feel more like a control abstraction.

What does this statement mean?

Mandroid
  • 6,200
  • 12
  • 64
  • 134

4 Answers4

15

This is syntactic sugar just for look and feel. When a function takes a function as argument like in

def doWith[A, B](todo: A => B): B = ???

You would normally have to call it like

doWith( input => ... )
// or even
doWith({ input => ... })

In scala it is allowed to replace parenthesis with with curlies, so

doWith { input =>
  ...
}

Has the look and feel of a control structure like

if (...) {
  ...
}

Imho, that makes calling higher order functions like 'map' or 'collect' much more readable:

someCollection.map { elem =>
  ...
  ...
}

which is essentially the same as

someCollection.map({ elem =>
  ...
  ...
})

with less chars.

Sascha Kolberg
  • 7,092
  • 1
  • 31
  • 37
3

"Control abstractions" are e.g. if, while, etc. So you can write a function

def myIf[A](cond: Boolean)(ifTrue: => A)(ifFalse: => A): A = 
    if (cond) ifTrue else ifFalse

(if you aren't familiar with : => Type syntax, search for "by-name parameters") you can call it as

val absX = myIf(x < 0) { -x } { x }

and it looks very similar to normal if calls. Of course, this is much more useful when the function you write is more different from the existing control structures.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
2

In addition to (regular) functions and by-name arguments, braces also help with partial functions:

processList(l) {
  case Nil => ...
  case h :: t => ...
}

and sequences of expressions:

doSomething {
  thing1;
  thing2
}

Note that (thing1; thing2) is not a valid expression in Scala like it would be in, say, ML.

1

The difference between curly braces {} and parenthesis () is that you can write multiple lines in the curly braces, while in parenthesis you cannot write more than one line for example.

val x :[List[Int]]=List(1,2,3,4,5,6,7,8)
x.map(y=> y*5) //it will work fine
x.map(y=> 
case temp:Int=>println(temp)
case _ => println(“NOT Int”)) //it will not work

x.map{y=> 
case temp:Int=>println(temp)
case _ => println(“NOT Int”)} //it willwork

So we can say it’s just the synthetic sugar to allow developer to write more then none line without ; that’s it it may have some other reason too.

kev
  • 8,928
  • 14
  • 61
  • 103
Raman Mishra
  • 2,635
  • 2
  • 15
  • 32