I don't understand when forAll deals with None values.
def areTheyEqual(x: Option[String], y: String) = {
if (x.forall(_ == y)) {
true
} else {
false
}
}
When I call the function:
areTheyEqual(None, "hello") this returns true, when I expect this to be false since they are not equal. Please help. Why is it like this?
Edit:
To solve this, I changed the if statement to:
if (x.nonEmpty && x.forall(_ == y))
But I still want to know why it returned true without the x.nonEmpty condition.
Generally speaking, the
forallmethod checks whether all of the objects in the collection satisfy some predicate. So what does it mean when it returnsfalse? Logically, it must mean that there is an element in the collection where the predicate isn't true. So doesNonecontain an element where the predicate isn't true? Obviously not, because it doesn't contain any element at all. Hence it would be wrong forforallto returnfalsein that case. So it all makes sense.The
existsmethod on the other hand will returnfalseif theOptionis empty.