Question

I see in and and or method of Predicate, the return type is Predicate, while in the return statement, there is a lambda expression doing logical and(or) with a boolean. So how the return statement is evaluate when the logical and(or) has one operand of Lamdba expression and another operand of boolean. Why is this valid ?

Below is code for and method of java.util.function.Predicate:

default Predicate<T> and(Predicate<? super T> other) {
    Objects.requireNonNull(other);
    return (t) -> test(t) && other.test(t);
} 
Was it helpful?

Solution

In this statement:

return (t) -> test(t) && other.test(t);

the && operator has higher precedence than the -> operator, so the expression is parsed as if:

return (t) -> (test(t) && other.test(t));

Thus, this returns the lambda expression itself, which is the logical AND of this predicate's test method with the other predicate's test method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top