Search code examples
scala

Scala: Filtering List of case class with fields of Option


I have a List[A] where A is a case class with a number of fields, from which x and y are Option[double]. I am trying to filter this list based on two conditions as below:

val resFiltered = res.filter(c => (c.x.getOrElse(num) != num) && 
                                  (c.y.getOrElse(num) != num)
                             )

where num is really a random number. I am basically filtering the list to get rid of As that either fields of x or y are null. Is there a more elegant way of doing this? Thanks.

Based on my search, this flatten approach can be useful, but it doesn't support the fields.


Solution

  • You say x and y are Option[Double] so they can't be null. It looks like this is what your code does...

    .filter(c => c.x.nonEmpty || c.y.nonEmpty)
    

    ...but you state that you want to "get rid of" if "either field...", which might mean that && should be used instead of ||.