I would like to add an element depending on the result of a different condition. As it is now, I did it this way :
val add1 = if(condition1) Seq(ENUM_ELEMENT_1) else Seq()
val add2 = if(condition2) Seq(ENUM_ELEMENT_2) else Seq()
return Seq(add1, add2).flatten
If I was in Java I would just create an empty ArrayList() at the beginning and add to this list as the code encounter the ifs. But in Scala, I would have to use a mutable object of Seq and I don't know if it's appropriate here.
Declare list of tuples with conditions on left and enums on right:
val conditions: Seq[(Boolean, Enum)] = List(
condition1 -> ENUM_ELEMENT1,
condition2 -> ENUM_ELEMENT2
)
Then you can just reduce it with collect
:
val result: Seq[String] = conditions.collect{
case (true, v) => v
}
or flatMap
:
val result: Seq[Enum] = conditions.flatMap{
case (true, v) => Some(v)
case _ => None
}
There is several ways to do this. Here's what come out of the blue to me:
(if(condition1) Seq(ENUM_ELEMENT_1) else Seq()) ++ (if(condition2) Seq(ENUM_ELEMENT_2) else Seq())
They are way of factorizing both of this procedure by a function or a fold but it may be overthinking at this state.
Without proper context I am unable to provide a more concrete solution, but I think this pseudo-code represents your problem.
If you have any questions, do not doubt to ask for clarification.
object ListFactory {
type Input = ???
type Output = ???
private val allElements: List[Output] =
List(ENUM_ELEMENT_1, ENUM_ELEMENT_2, ???)
private val conditions: List[Input => Boolean] =
List(???)
def apply(input: Input): List[Output] =
(allElements zip conditions).collect {
case (element, condition) if (condition(input)) => element
}
}
ListFactory(???) // res1: List[Output] = ???
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With