TrayMan
TrayMan

Reputation: 7445

How to flatMap Scala collection and retain original value in the result?

Consider a function f : A -> Option[B].

I want to flatMap using f, but keep the original value in the result as well, as a pair of values (A,B).

I can write it like this:

collection.flatMap(a => {
  f(a) match {
    case Some(b) => Some((a,b))
    case None => None
  }
})

But is there a nicer way?

Upvotes: 0

Views: 168

Answers (2)

jwvh
jwvh

Reputation: 51271

This also works.

for {
  a <- collection
  b <- f(a)
} yield (a,b)

Upvotes: 6

Jatin
Jatin

Reputation: 31724

How about this?

collection.flatMap(a => f(a).map(b => (a,b)))

Upvotes: 3

Related Questions