Randomize
Randomize

Reputation: 9103

Scala: build Map with pattern matching

I am trying to build a Map[String, Any] like this:

Map(
  somevalues match {
   Some(v) => ("myvalues -> v)
   None => ???
},

  othervalues match {
   Some(v) => ("othervalues -> v)
   None => ???
},
...etc
)

which value should I use for the none case as I don't want to insert anything in the map in that case?

Upvotes: 1

Views: 147

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170735

Consider

List(
  someValues match {
    case Some(v) => Some("myValues" -> v)
    case None => None
  },

  otherValues  match {
    case Some(v) => Some("otherValues" -> v)
    case None => None
  },
  ...
).flatten.toMap

or shortened:

List(
  someValues.map("myValues" -> _),

  otherValues.map("otherValues" -> _),
  ...
).flatten.toMap

Upvotes: 3

Related Questions