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?
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.
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With