Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8: Why a lambda expression could do a logical and(or) with boolean

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);
} 
like image 456
user2018791 Avatar asked Nov 25 '25 15:11

user2018791


1 Answers

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.

like image 145
Stuart Marks Avatar answered Nov 27 '25 05:11

Stuart Marks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!