Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curly braces in Scala method call [duplicate]

Tags:

scala

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?

like image 208
Mandroid Avatar asked Apr 07 '18 11:04

Mandroid


2 Answers

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.

like image 156
Sascha Kolberg Avatar answered Sep 24 '22 16:09

Sascha Kolberg


"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.

like image 44
Alexey Romanov Avatar answered Sep 25 '22 16:09

Alexey Romanov