views:

256

answers:

1

In Chapter 3 of Programming Scala, the author gives two examples of for loops / for comprehensions, but switches between using ()'s and {}'s. Why is this the case, as these inherently look like they're doing the same thing? Is there a reason breed <- dogBreeds is on the 2nd line in example #2?

// #1 ()'s
for (breed <- dogBreeds
  if breed.contains("Terrier");
  if !breed.startsWith("Yorkshire")
) println(breed)

// #2 {}'s
for {
  breed <- dogBreeds
  upcasedBreed = breed.toUpperCase()
} println(upcasedBreed)
+5  A: 

If you read the green Tip:

for expressions may be defined with parenthesis or curly braces, but using curly braces means you don’t have to separate your filters with semicolons. Most of the time, you’ll prefer using curly braces when you have more than one filter, assignment, etc.

So for comprehension with () and {} are the same the only thing that change is the separator used : for () you have to use a semicolon ";" as separator and for {} you use new line.

Patrick
Another one of Scala's WTF features. A great language, but littered with sugar that's not only unnecessary, but arguably harmful.
arcticpenguin
Semicolon inference doesn't come for free. The other time it bites is `val a = 1 + 2 + 3 <nl> + 4`. This is parsed as `val a = 1.+(2).+(3); 4.unary_+()`
retronym
Note that the first example doesn't compile.
retronym
@arcticpenguin Scala's semicolon inference makes perfect sense (and you're unlikely to screw it up) if you've programmed in Ruby.
Ken Bloom
@Ken I programmed in ruby, and the semicolon inference rules doesn't make too much sense for me.
Elazar Leibovich