Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Scope on Scala's For Loops (For Comprehension)

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)
like image 717
T. Stone Avatar asked May 29 '10 22:05

T. Stone


1 Answers

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.

like image 79
Patrick Avatar answered Nov 12 '22 20:11

Patrick