In a lot of Scala examples I see people use curly braces in places I find outright strange, when the same statement could easily be written using parentheses.
Example:
lst foreach (x => println(s"the value returned is: $x")) // parens
lst foreach {x => println(s"you get the idea, $x")} // braces
I understand that you can use braces as an alternative to parentheses, simply because it allows you to write a statement on multiple lines:
val res = for {
x <- coll1
y <- coll2
} yield (x, y)
Curly brackets are rarely used in prose and have no widely accepted use in formal writing, but may be used to mark words or sentences that should be taken as a group, to avoid confusion when other types of brackets are already in use, or for a special purpose specific to the publication (such as in a dictionary).
Do not confuse brackets [ ] with parentheses ( ). Parentheses are used to enclose additional information in your own writing; brackets are editorial marks used to insert comments into someone else's words that you are quoting, or to insert material into a passage already in parentheses.
Parentheses, brackets, and braces are ways of separating parts of a mathematical expression from one another, and they all look quite similar. Parentheses are smooth and curved ( ), brackets are square [ ], and braces are curly { }. In mathematics, they are mostly used for order of operations.
Round Brackets or Parentheses British English. ( ) = round brackets or brackets. American English. ( ) = parentheses. Round brackets are basically used to add extra information to a sentence.
In general, there are many cases when you would prefer curly braces (e.g. multiline expressions, for comprehensions), but let's talk specifically about
when it's written on a single line, is there any inherent reason to use one over the other
In a second case it's not just curly braces, instead of parentheses, it's curly braces with ommited parentheses. Scala allows you to ommit parenthesis sometimes, and the later syntax is used to access to the niceties you got in partial functions (namely, pattern matching), so
lst foreach {x => println(s"you get the idea, $x")}
is actually
lst foreach({x => println(s"you get the idea, $x")})
which, as I said, can be useful from pattern matching POV:
val map = Map("foo" -> "bar")
map foreach { case (k, v) => println(s"key: $k, value: $v") }
// which is not possible with the usual parenthesis
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