문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top