Java 8+ allows assigning method references to Functional Interfaces.
Then what is the problem with below code (jdoodle link) -
public void newMethod(){
Predicate p = String::isBlank;
}
Different from the error in jdoodle compilation, in my local (gist link) i get error:
Non-static method cannot be referenced from a static context
But - below thing worked
Predicate<String> pp = String::isBlank; //this thing works
This is because you are using a raw type -
Predicate. The function type of a raw functional interface is:The function type for the generic
Predicate<T>is(T) -> boolean(pardon my own original syntax here), a function that takes in aTand returns aboolean. Therefore, the function type of the rawPredicateis(Object) -> boolean, the erasure of(T) -> boolean.This means that it is possible to assign
Objects::isNullto such a raw functional interface (but you shouldn't use raw types in the first place):The method reference
String::blankonly takes aString, not any kind ofObject. Therefore it is not congruent with the the function type(Object) -> booleanand hence cannot be assigned to a variable of typePredicate.If
Predicate p = String::isBlank;had worked, then you would be able to do something likep.test(1). AndString::isBlankwould have to magically determine whether1"is blank".The error message here is admittedly a bit confusing.
For
Predicate<String>, the definition of its function type is different, and it has the function type(String) -> boolean, which the method referenceString::isBlankis congruent to.