This is my first code:
public class MethodReference {
public static void main (String []args) {
Stream<String> s = Stream.of("brown bear", "grizzly");
s.sorted(Comparator.reverseOrder()).forEach(System.out::print);
//...
}
}
Result: grizzlybrown bear
This is my second code:
public class MethodReference {
public static void main (String []args) {
Stream<String> s = Stream.of("brown bear", "grizzly");
s.sorted(Comparator::reverseOrder()).forEach(System.out::print);
//...
}
}
Result: compiler error
My questions: Why is there a compiler error in the second code? Can't I use the method reference for static method of functional interface?
I know I can't use method reference with default method of functional interface. I know I can use method reference with a class in 5 cases:
Class
Class::staticMethod
Class::instanceMethod
instance::instanceMethod
Class::new
Functional Interface
- Interface::abstractMethod
Thanks a lot!
Comparator.reverseOrder()
is an expression which resolves to the Comparator
type, because that's what it returns.
Comparator::reverseOrder
is an expression which resolves to a method which takes no arguments and returns a Comparator
e.g. a Supplier<Comparator<String>>
, though it could be any matching functional interface.
In the second instance you are trying to pass a method (which provides a Comparator
) as an argument. The method doesn't want that - it just wants the Comparator
itself.
You could think of it like this (just pseudo-code to demonstrate the point):
s.sorted(new Comparator())
vs
s.sorted(new Supplier(new Comparator()))
To answer your second question as to whether it's ever possible to use a method reference for a static method of an interface - yes, absolutely!
If we declare the following method:
<T> void giveMeAComparatorSupplier(Supplier<Comparator<T>> supplier) { }
then we can definitely call it with a method reference
giveMeAComparatorSupplier(Comparator::reverseOrder);
(And FYI your method reference syntax is wrong - it never uses ()
)