Reputation: 10751
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.
Upvotes: 1
Views: 4220
Reputation: 1436
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
}
}
Upvotes: 4
Reputation: 51271
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
Upvotes: 1