0

So say we're given a List[String] and bunch of Option[String]'s call them a, b, c. Say I want to append the valid (Some's) Options[String]'s out of a, b, c to my existingList[String]. What would be the best way to go about this using immutable structures?

I.e. I know I could use a ListBuffer and do something like:

def foo(a: Option[String], b: Option[String], c: Option[String]) : ListBuffer[String] = {
    val existingList = new ListBuffer("hey")
    a.map(_ => existingList += _)
    b.map(_ => existingList += _)
    c.map(_ => existingList += _)
}

but I want to use immutable structures.

3 Answers3

4

Use .flatten on a list of options and append it to your list

val existingList = List(1, 2, 3)
val a = Some(4)
val b = None
val c = Some(5)

val newList = existingList ::: List(a, b, c).flatten
Alex
  • 7,460
  • 2
  • 40
  • 51
0
def foo(a: Option[String], b: Option[String], c: Option[String]): List[String] =
    List("hey") ++ a.toList ++ b.toList ++ c.toList

which is similar to flatten or flatMap.

scala> foo(Some("a"), None, Some("c"))
res1: List[String] = List(hey, a, c)

It's better to define a generic function like this:

def foo[T](xs: Option[T]*) : List[T] =
    xs.toList.flatten

scala> foo(Some("a"), None, Some("c"))
res2: List[String] = List(a, c)
yǝsʞǝla
  • 16,272
  • 2
  • 44
  • 65
-1

Let val list = List("A", "B", "C") and val opts = = List(Some("X"), None, Some("Y"), None, Some("Z")). Then list ++ opts.filter(_.isDefined).map(_.get) will give an new List("A", "B", "C", "X", "Y", "Z") with all elements from list and all non-empty elements of opts.

Andreas
  • 27
  • 4