First: to turn a Option[String] into a String :
opt.getOrElse("")
or if you prefer a more syntactic call to the operator call:
opt getOrElse ""
then getOrElse can be shortened with an alias | provided by Scalaz :
import scalaz._, Scalaz._ opt | ""
Alternatively, you can let Scalaz figure out what the "" for you; this works thanks to having a Monoid instance defined for String that defines the empty (or null) String value for the empty string:
opt.orZero
Total:
scala> ("hello".some).orZero + " blabla " + ("world".some).orZero res9: String = hello blabla world scala> (none[String]).orZero + " blabla " + ("world".some).orZero res10: String = " blabla world" scala> ("hello".some).orZero + " blabla " + (none[String]).orZero res11: String = "hello blabla "
(here I use Scalaz none and some , with Scala vanilla you need to write None: Option[String] and Some("hello"): Option[String to get the types you need)
However ... you probably want to avoid this extraneous space, so in practice you would use something in the lines; above all for training / research:
scala> List("hello".some, Some("blabla"), "world".some).flatten.mkString(" ") res0: String = hello blabla world scala> List("hello".some, none[String], "world".some).flatten.mkString(" ") res1: String = hello world
- note that between words there is always only one space between words.
source share