Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda as a combination of methods from the Predicate interface doesn't compile if it is written as one statement

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.

like image 617
daniel Avatar asked May 03 '18 10:05

daniel


People also ask

Can a predicate be null?

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.

What is predicate in Java?

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.

What is predicate and function in Java 8?

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.


1 Answers

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>).
like image 134
Vadym Pechenoha Avatar answered Sep 21 '22 00:09

Vadym Pechenoha