Reputation: 603
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
Upvotes: 0
Views: 934
Reputation: 149548
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
Upvotes: 7