Reputation: 3897
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
Reputation: 10776
In your case third part can be Option
al:
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
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