Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten a Map of Option to Map [duplicate]

Tags:

scala

I have a Map[A, Option[B]], what is the optimal way to make a flatten to get a Map[A, B] ?

I know for a list we can use flatten, but this structure is different

like image 931
nam Avatar asked Sep 15 '15 15:09

nam


1 Answers

Well, they are not the same, so you will need a way to define what happens if a value is None. I assume you want to ignore those keys, if so, you can collect with a partial function:

map.collect {
  case (k, Some(v)) => k -> v
}

or use a for-comprehension

  for ((k, Some(v)) <- map) yield k -> v
like image 149
Daniel Langdon Avatar answered Nov 16 '22 22:11

Daniel Langdon