Makar Nikitin
Makar Nikitin

Reputation: 329

How to call getOrElse + foreach

Say i have case class with Option[Map[String, String] on it, and i want to iterate throw it.

This code works in Scala 2.13, but in Scala 2.11 build fails.

some.getOrElse(None).foreach {
case (key: String, value: String) =>
  if true doSomething
}

It says that Cannot resolve symbol foreach How to fix that?

Upvotes: 0

Views: 345

Answers (2)

pedrorijo91
pedrorijo91

Reputation: 7845

why not default to an empty map?

some.getOrElse(Map.empty()).foreach {
case (key: String, value: String) =>
  if true doSomething
}

Upvotes: 1

Tim
Tim

Reputation: 27356

It does not compile on 2.13 (or 2.12) so there is clearly an issue with your code.

What I think you are trying to do is this:

some.map(_.map {
  case (key: String, value: String) =>
    ???
})

This will return None if some is None, otherwise it will call map on the Map and return the result in Some(?).

Upvotes: 1

Related Questions