Search code examples
scalaforall

Using forall() in extracting String from Option[String] in scala


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.


Solution

  • Generally speaking, the forall method checks whether all of the objects in the collection satisfy some predicate. So what does it mean when it returns false? Logically, it must mean that there is an element in the collection where the predicate isn't true. So does None contain an element where the predicate isn't true? Obviously not, because it doesn't contain any element at all. Hence it would be wrong for forall to return false in that case. So it all makes sense.

    The exists method on the other hand will return false if the Option is empty.