简体   繁体   中英

How can I avoid using an interface in java 8?

I just want to know if its possible to avoid the use of an interface in this code

public interface FunctionT<T,R>  {
        R apply(Integer...args);
}
public static FunctionT sum = (params) ->  Arrays.asList(params)
                                                                .stream()
                                                                .reduce(Integer::sum).get();

The type of a lambda expression in Java is a functional interface . This means that the lambda must be provided with a target type that is a functional interface. This could be yours ( FunctionT ) or a standard one like java.util.function.Function .

Put another way, function types in Java are nominal , not structural.

(Also, you don't want to blindly call get() on an Optional , you want to use one of the safe methods like orElse() or ifPresent() . Otherwise you lose all the safety of using Optional in the first place.)

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