Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

scala - Why use curly braces over parentheses?

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) 
  • So when it's written on a single line, is there any inherent reason to use one over the other?
  • The outcome should be the same in the end, or am I missing something?
  • Or is it simply just a matter of style and/or personal taste?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...