Scala: add items to a sequence or merge sequences conditionally
Asked Answered
M

3

5

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

Metagenesis answered 8/1, 2016 at 19:33 Comment(0)
D
10

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.

Diahann answered 8/1, 2016 at 19:51 Comment(0)
H
2

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

Hanes answered 8/1, 2016 at 22:22 Comment(0)
I
2

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)
Idolatry answered 9/1, 2016 at 7:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.