7

This is my first day of studying Scala (using the "Beginning Scala" book). When I read the for loops in Scala, there are 2 examples:

val books = List("Beginning Scala", "Beginning Groovy", "Beginning Java", "Scala in easy steps", "Scala in 24 hours")

[1]

for (book<-books if book.contains("Scala")) println(book)

[2]

for { book <- books
  bookVal = book.toUpperCase()
}
println(bookVal)

The thing that confused me is:

In [1] for uses parentheses "()" to wrap the loop control block while in [2] it uses curly braces "{}". I wonder if this is just different syntax but the same purpose or if they actually mean something different?

Thanks

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
Kuan
  • 11,149
  • 23
  • 93
  • 201
  • 1
    Related question: http://stackoverflow.com/questions/4386127/what-is-the-formal-difference-in-scala-between-braces-and-parentheses-and-when – Kulu Limpa Aug 10 '15 at 19:45
  • @KuluLimpa Thanks , this helps though too complicated for me to understand. – Kuan Aug 10 '15 at 20:19

1 Answers1

4

Curly braces are usually used if you have multiline expression or expression which contains few other experession. If you're able (or want) to write in single line using semicolons you may use parentheses. Every for loop you can write with curly braces but using of parentheses is reduced.

If some other case curly braces allow you to use easier syntax to write partial function or pattern matching.

If you write in REPL following code:

for (
    i <- List(1,2,3)
    y = i * i
) yield y

it wouldn't compile e.g.

Sergii Lagutin
  • 10,561
  • 1
  • 34
  • 43
  • Thanks, I tried putting multi lines in "()", and it works, I do not know what exactly the diff between {} and (), why they are woking in almost everywhere? There must be a lot of wrong about my understanding, could you give me some examples that only () can be used in FOR and vice versa? – Kuan Aug 10 '15 at 19:04
  • Thanks, I guess I get it(not sure, but guess so). I will try more. BTW, I wonder what kinda of operation can be considered as Expression? – Kuan Aug 10 '15 at 19:15
  • @Kuan In Scala every piece of code that return value is expression – Sergii Lagutin Aug 10 '15 at 19:18
  • Thanks. I guess I will just try more example to make myself comfortable with this concept. – Kuan Aug 10 '15 at 19:57