Scala Option[Seq[A]] exists

4k views Asked by At

I have the following code:

case class Person(name: String, age: Int)

object Launcher extends App {

  val people = Option(Seq(Person("Andrii", 20), Person("John", 35), Person("Sam", 15)))

  def filterPeople(list: Option[Seq[Person]]): Boolean =
    list.getOrElse(Nil)
      .exists(_.age < 18)

  assert(filterPeople(people) == true)
}

The question is: can I process Option[Seq[A]] more elegantly and safely without getOrElse(Nil)?

list.getOrElse(Nil)
      .exists(_.age < 18)

I have found another approach to this:

list.exists(_.exists(_.age > 18))

Note: I have Option[Seq[A]] just because of REST contract.

2

There are 2 answers

4
Camilo Sampedro On BEST ANSWER

Pointed by @NimrodArgov, I would prefer to use pattern matching for checking the list type as it is more readable:

def filterPeople(list: Option[Seq[Person]]): Boolean = {
  list match {
    case Some(people) => people.exists(_.age < 18)
    case None => false
  }
}
2
jwvh On

Another possibility.

def filterPeople(list: Option[Seq[Person]]): Boolean =
  list.fold(false)(_.exists(_.age < 18))

Tested:

filterPeople(people)  // res0: Boolean = true
filterPeople(None)    // res1: Boolean = false