What is the difference between both these ways of lambda creation? Why doesn't the first one compile?
Predicate<Integer> predicate = Predicate.isEqual(0).or(Predicate.isEqual(1));
Gives:
error: incompatible types: Predicate<Object>
cannot be converted to Predicate<Integer> = Predicate.isEqual(0).or(Predicate.isEqual(1));
Predicate<Integer> pred21 = Predicate.isEqual(0);
Predicate<Integer> pred22 = pred21.or(Predicate.isEqual(1));
This one works.
The NULL predicate tests for null values. The result of a NULL predicate cannot be unknown. If the value of the expression is null, the result is true. If the value is not null, the result is false.
The predicate is a predefined functional interface in Java defined in the java. util. Function package. It helps with manageability of code, aids in unit-testing, and provides various handy functions.
Function interface is used to do the transformation.It can accepts one argument and produces a result. On the other side, Predicate can also accept only one argument but it can only return boolean value. It is used to test the condition.
Adding <Integer>
before the isEqual
method call should help :
Predicate<Integer> predicate = Predicate.<Integer>isEqual(0).or(Predicate.isEqual(1));
The reason behind such compiler behavior:
isEqual
is a static generic method which returns Predicate<T>
(no matter what actual type of its input parameter is), so it returns Predicate<Object>
when calling the method without specifying returning type explicitly.or
is also a static generic method, but it returns a predicate parametrized by the same type, as its input parameter (which is Predicate<Object>
).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With