sant016
sant016

Reputation: 345

How to apply a filter with FP/scala

I have a class that has some Option values, and I need to apply all the values that come as Some in the class to a list of objects.

Example:

class Thing(name: String, age: Int)
class Filter(name: Option[String], age: Option[Int], size: Option[Int])
val list: List[Thing] = functionThatReturnsAListOfThings(param)
val filter: Filter = functionThatReturnsAFilter(otherParam)
list.filter{ thing => 
  if filter.name.isDefined {
    thing.name.equals(filter.name.get)
  }
  if filter.age.isDefined {
    thing.age == filter.age.get
  }
}.take{
  if filter.size.isDefined filter.size.get
  else list.size
}

How can I apply the filter to the list properly with FP?

Upvotes: 0

Views: 45

Answers (1)

jwvh
jwvh

Reputation: 51271

First off we need to make a small change so that the constructor arguments are public members.

class Thing(val name: String, val age: Int)
class Filter(val name : Option[String]
            ,val age  : Option[Int]
            ,val size : Option[Int])

Next, it's not clear, from your example code, what should happen when filter.name and filter.age are both None. I'll assume that None means true, i.e. not filtered out.

list.filter { thing =>
  filter.name.fold(true)(_ == thing.name) &&
    filter.age.fold(true)(_ == thing.age)
}.take(filter.size.getOrElse(Int.MaxValue))

Note that take(Int.MaxValue) is a bit more efficient than take(list.size).

Upvotes: 1

Related Questions