Pure Scala syntax for "Add optional value to Seq, if one exists"

I often see these two patterns for adding an optional value to 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 these methods work, but they seem verbose and ugly. Is there an existing operator or method to make this more natural / functional?

Thanks!

+6
source share
2 answers

The option is implicitly converted to a sequence with 1 or 0 elements, 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) 
+17
source
 maybeFoo.foldLeft(fooList)(_ :+ _) 
+4
source

Source: https://habr.com/ru/post/1011789/


All Articles