stack0114106
stack0114106

Reputation: 8711

scala for comprehension throwing error for Map

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

Answers (2)

user51
user51

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)
  1. A for comprehension should always start with <- in its first statement which creates the context for the remaining expression that are following.

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

Pedro Correia Lu&#237;s
Pedro Correia Lu&#237;s

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

Related Questions