Question

I want to replace a value inside an Option iff it is non-empty. I can do it using a constant function using map(_ => newValue) like in

Some("text").map(_ => 42)

Is there a more concise way, like Haskell's <$ in 42 <$ Just "text"?

Était-ce utile?

La solution

Scalaz:

scala> 1.some >| "x"
res0: Option[String] = Some(x)

scala> none[Int] >| "x"
res1: Option[String] = None

You could use as instead of >|.

If you are looking for something "like in Haskell" you probably should take a look at Scalaz.

Autres conseils

IMO that's pretty concise already. It doesn't get any shorter than that with the standard library. (See below for an answer using Scalaz.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top