Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to contruct a Seq depending on different conditions that follows each other

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.

like image 347
Robert Reynolds Avatar asked May 16 '19 16:05

Robert Reynolds


3 Answers

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
}
like image 92
Krzysztof Atłasik Avatar answered Oct 17 '22 01:10

Krzysztof Atłasik


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.

like image 45
Benjamin Vialatou Avatar answered Oct 17 '22 01:10

Benjamin Vialatou


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] = ???
like image 28
Luis Miguel Mejía Suárez Avatar answered Oct 17 '22 00:10

Luis Miguel Mejía Suárez