Clean Scala syntax for "Append optional value to Seq if it exists"

functional-programming, scala

Solution

Option implicitly converts into a sequence with 1 or 0 items so the following works:

scala> val opt = Some("a")
opt: Some[String] = Some(a)

scala> val nope = None
nope: None.type = None

scala> val seq = Seq("a", "b", "c")
seq: Seq[String] = List(a, b, c)

scala> seq ++ opt
res3: Seq[String] = List(a, b, c, a)

scala> seq ++ nope
res4: Seq[String] = List(a, b, c)

Problem

I often see these two patterns for appending an Optional value to a Seq: ``` def example1(fooList: Seq[Foo], maybeFoo: Option[Foo]): Seq[Foo]) = { if (maybeFoo.isDefined) fooList :+ maybeFoo.get else fooList } def example2(fooList: Seq[Foo], maybeFoo: Option[Foo]): Seq[Foo]) = { maybeFoo match { case Some(foo) => fooList :+ foo case None => fooList } } ``` Both of those methods work, but they seem verbose and ugly. Is there an existing operator or method to do this more naturally/functionally? Thanks!

Original source