Reputation: 8711
I have the below code snippet, the regular for loop works fine. But the for comprehension throws error
println("Using for loop")
for( (key, value) <- orec.groupBy(x => x.continent) )
{
println(key + value.length )
}
println("Using for comprehension")
for{
(key, value) <- orec.groupBy(x => x.continent)
println(key + value.length )
} yield (key,value)
The Error message is
Error:(84, 5) '<-' expected but '}' found.
} yield (key,value)
I could not understand what is wrong with the code. Please help in fixing the issue
Upvotes: 1
Views: 108
Reputation: 10143
println
doesn't work within for
comprehension just like that. It should be like below.
for {
(key, value) <- orec.groupBy(x => x.continent)
_ = println(key + value.length )
} yield (key,value)
A for comprehension should always start with <- in its first statement which creates the context for the remaining expression that are following.
All <-
within for comprehension does flatMap
expect last one which does map
.
You should use _ =
for side effecting tasks which doesn't conform to initial context established by for comprehension.
I recommend this tutorial . It explains for comprehensions more elegantly.
Upvotes: 6
Reputation: 1095
You can´t have prints like that inside a for comprehension, you can use them like this:
for{
(key, value) <- orec.groupBy(x => x.continent)
} yield println(key + value.length )
Upvotes: 2