1

If I have a case class defined as:

case class Foo(bar: Option[String])

and a variable baz: Option[Foo], what's the most idiomatic way to extract bar from baz while providing a default value like an empty string?

Right now, I have

baz.fold("")(_.bar.getOrElse(""))

but having the empty string in there twice makes me think there's a better way.

mplis
  • 748
  • 2
  • 6
  • 19
  • 2
    Do *not* use `getOrElse`. See my answer to a previous question for more details: http://stackoverflow.com/questions/21923600/scala-option-map-vs-pattern-matching/21936653#21936653 – vptheron Jun 18 '14 at 17:06
  • I actually never noticed that `getOrElse` didn't force you to use the same type that's inside the `Option`. Why was it designed that way? – mplis Jun 19 '14 at 16:26
  • This is due to the covariance of the type parameter A in `Option[+A]`. There are a lot of resources to read more about that, one example: http://stackoverflow.com/questions/14584830/covariant-type-t-occurs-in-contravariant-position – vptheron Jun 19 '14 at 17:11

1 Answers1

6

How about:

baz.flatMap(_.bar).getOrElse("")

Or per @vptheron's comment:

baz.flatMap(_.bar).fold("")(identity)
Michael Zajac
  • 55,144
  • 7
  • 113
  • 138