Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 925
Nathan Avatar asked Oct 27 '16 19:10

Nathan


2 Answers

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)
like image 76
Angelo Genovese Avatar answered Oct 31 '22 03:10

Angelo Genovese


maybeFoo.foldLeft(fooList)(_ :+ _)
like image 25
jwvh Avatar answered Oct 31 '22 05:10

jwvh