user2300867 user2300867 - 1 month ago 8
Scala Question

Applying a predicate to all elements of a sequence

How should I write a function that returns true if all elements in a list satisfy a given predicate?

Considering list below and any predicate:

val set = List(3, 4, 5, 6, 10)


I assume I need to write something similar to:

def checkListElements(list parameters... ): Boolean = true if condition meet else false

Answer

You don't need to write one yourself, you can use Iterator.forall:

scala> var list = List(1,2,3,4,5)
set: List[Int] = List(1, 2, 3, 4, 5)

scala> list.forall(i => i % 2 == 0)
res0: Boolean = false

A little shorter using syntax sugar:

scala> list.forall(_ % 2 == 0) // Underscore will expand to i => i % 2 == 0
res2: Boolean = false