Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 410
ab_732 Avatar asked Jan 08 '16 19:01

ab_732


3 Answers

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.

like image 139
4e6 Avatar answered Nov 18 '22 06:11

4e6


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

like image 37
Dima Avatar answered Nov 18 '22 06:11

Dima


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)
like image 2
elm Avatar answered Nov 18 '22 06:11

elm