ab_732
ab_732

Reputation: 3897

Scala: add items to a sequence or merge sequences conditionally

I need to add an item to a Seq depending on a condition.

The only thing I have been able to do is:

if(condition){
    part1 ++ part2 ++ Seq(newItem)
}
else {
  part1 ++ part2
}

part1 and part2 are Seq[String]. It works but there is a lot of repeated code. Any way to do this better? Thank you

Upvotes: 5

Views: 3805

Answers (3)

4e6
4e6

Reputation: 10776

In your case third part can be Optional:

val part3 = if (condition) Some(newItem) else None
part1 ++ part2 ++ part3

Example:

scala> Seq(1,2,3) ++ Seq(4,5) ++ Option(6)
res0: Seq[Int] = List(1, 2, 3, 4, 5, 6)

Here implicit conversion Option.option2Iterable is doing the trick.

Upvotes: 10

elm
elm

Reputation: 20415

Consider also Seq.empty on an if-else expression, as follows,

part1 ++ part2 ++ (if (condition) Seq(newItem) else Seq.empty)

For instance

Seq("a") ++ Seq("b") ++ (if (true) Seq("c") else Seq.empty)
List(a, b, c)

Seq("a") ++ Seq("b") ++ (if (false) Seq("c") else Seq.empty)
List(a, b)

Upvotes: 2

Dima
Dima

Reputation: 40500

part1 ++ part2 ++ Some(newItem).filter(_ => condition)

Upvotes: 2

Related Questions