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

  • A+

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.

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>).


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: