mplis
mplis

Reputation: 768

Extract Option from case class while ignoring None

I have a sequence of case classes like this

case class Foo(..., bar: Option[A], ...)

and I want to turn it into a Seq[(Foo, A)], where I extract the A from bar and the Seq only contains Foo's where bar is not None. Here's the implementation I have now, but the fact that it calls get makes me think there's a better way to do this:

val seqOfTuples = seqOfFoos.collect {
    case foo if foo.bar.isDefined => (foo, foo.bar.get)
}

Upvotes: 1

Views: 129

Answers (1)

Jens Halm
Jens Halm

Reputation: 499

val seqOfTuples = seqOfFoos.collect {
  case f @ Foo(_, Some(a), _) => (f, a)
}

You might need to adjust the number of underscores, depending on how many other parameters Foo has.

Upvotes: 8

Related Questions