How to merge two Option[String] variables into one when using flatMap in Scala?
Here's one approach
List(firstName, lastName).flatten match {
case Nil => None
case xs => Some(xs.mkString(" "))
}
quick testing in the REPL...
scala> def fullName(fn: Option[String], ln: Option[String]): Option[String] = {
| List(fn, ln).flatten match {
| case Nil => None
| case xs => Some(xs.mkString(" "))
| }
| }
fullName: (fn: Option[String], ln: Option[String])Option[String]
scala> fullName(None, None)
res3: Option[String] = None
scala> fullName(Some("a"), None)
res4: Option[String] = Some(a)
scala> fullName(None, Some("b"))
res5: Option[String] = Some(b)
scala> fullName(Some("a"), Some("b"))
res6: Option[String] = Some(a b)
I think that's a good application of a for
.
case class User(id: UUID, profiles: List[Profile]) {
// Skipped some lines
def fullName(loginInfo:LoginInfo): Option[String] = for {
profile <- profileFor(loginInfo)
first <- profile.firstName
last <- profile.lastName
} yield s"$first $last"
}
map2
(see chapter 4 of "the red book") affords you some abstraction:
def map2[A, B, C](oa: Option[A], ob: Option[B])(f: (A, B) => C): Option[C] =
for {
a <- oa
b <- ob
} yield f(a, b)
Then, leaving the LoginInfo
stuff out (because you didn't define profileFor
anywhere), you can simply define fullName
as
def fullName: Option[String] = map2(firstName, lastName) { _ + " " + _ }