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)
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
.
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