Arne Claassen
Arne Claassen

Reputation: 14414

Conditionally adding an Option to a List

If I want to add the value of an Option (should it have one) to a List, is there a better way than:

val x = Some(42)
val xs = List(1,2,3)
val xs2 = x match {
  case None => xs
  case Some(x2) => x :: xs
}

I know I can use the ++ operator on Iterable like this:

val xs2 = (x ++ xs).toList     

But does that explicit conversion back to List cause the entire list to be scanned and copied?

Upvotes: 5

Views: 1413

Answers (2)

childofsoong
childofsoong

Reputation: 1936

How about this:

val x: Option[Int] = Some(42)
val xs = List(1,2,3)
val xs2 = xs ++ (x match {
  case Some(value) => List(value)
  case None => List()
})

Note that I had to tell Scala that x is an Option[Int] so that it wouldn't assume it was a Some[Int] and complain about the matching.

Upvotes: 1

Marth
Marth

Reputation: 24832

You can use ++: to return a List instead of an Iterable (skipping the .toList call) :

scala> val x = Some(42)
x: Some[Int] = Some(42)

scala> val xs = List(1,2,3)
xs: List[Int] = List(1, 2, 3)

scala> x ++: xs
res4: List[Int] = List(42, 1, 2, 3)

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

scala> x ++: xs
res5: List[Int] = List(1, 2, 3)

Upvotes: 2

Related Questions