简体   繁体   中英

Java 8 Functional Interface Default and Static methods Return Type same as Functional Interface name?

In java 8 Functional Interface why the default and static methods should have a return type as Same Functional Interface name.

@FunctionalInterface
public interface Comparator<T> {

    public int compare(T t1, T t2);

    public default Comparator<T> thenComparing(Comparator<T> cmp){
        return (p1,p2)->compare(p1,p2)==0?cmp.compare(p1, p2):compare(p1,p2);
    } // return an int

    public default Comparator<T> thenComparing(Function<T,Comparable> f){
        return thenComparing(comparing(f)); // return an int
    }

    public static <U>Comparator<U> comparing(Function<U,Comparable> f){
        return (p1,p2)->f.apply(p1).compareTo(f.apply(p2)); // return an int
    }
}

They don't have to. Methods can be void or return whatever.

It just happens that Comparator has static and default methods that return Comparator , but this is just casual.

Many default methods return the self type because this allows for method chaining.

The default static methods define as return type only what they need.

For Comparator it makes sense to return a Comparator as these methods are factory methods.

Looks at other Functional Interfaces that have default static methods and you will see different things.
For example : Iterable.forEach() is defined as default void forEach(Consumer<? super T> action)

Static/default methods in functional interfaces don't get special treatment. They work like any other default/static methods in an ordinary interface. They can return whatever they like.

You see the static/default methods in a functional interface return the same type a lot because it makes sense to put them there.

For example, where else would you put the comparing method? In Consumer<T> or Supplier<T> ? No, it only makes sense to put it in Comparator<T> . For the thenComparing methods, it's because it's useful and very readable to just call them on a comparator object:

Comparator.comparing(x -> x.something).thenComparing(x -> x.somethingElse)

If you write your own functional interface and you think of some operation that can be done on it that transforms it into another functional interface, then add it in! Write a default method that returns another type!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM