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!
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)
maybeFoo.foldLeft(fooList)(_ :+ _)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With