此表达式的目标类型必须是功能接口

use*_*315 14 java eclipse java-8 eclipse-luna

我创建了一个函数来过滤多个谓词,我为它们执行逻辑AND:

@SafeVarargs
public static <T> Stream<T> filter(Stream<T> source, Predicate<T>... predicates) {
    return source.filter(Arrays.stream(predicates).reduce(predicates[0], Predicate::and));
}  
Run Code Online (Sandbox Code Playgroud)

致电时:

filter(IntStream.range(0, 10).boxed(), x -> x % 2 != 0, x -> x%3 == 0).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)

它工作正常并打印3和9.但是,当我传递一个谓词,如:

filter(IntStream.range(0, 10).boxed(), x -> x % 2 != 0).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)

我收到编译错误:

The target type of this expression must be a functional interface
Run Code Online (Sandbox Code Playgroud)

为什么是这样?

在此输入图像描述 对于infos我使用Eclipse Luna版本1.

Hol*_*ger 8

这是编译器的一个极端情况.为了确定是否应该将参数的varargs包装到数组中或者只是传递一个数组,它需要知道最后一个参数的类型,但是,在lambda表达式的情况下,它需要调用的方法签名来确定类型.但很明显应该发生什么,因为lambda表达式永远不能是一个数组类型,因此,javac编译它没有问题.

一个可接受的解决方法是重载方法:

@SafeVarargs
public static <T> Stream<T> filter(Stream<T> source, Predicate<T>... predicates) {
    return source.filter(
        Arrays.stream(predicates).reduce(predicates[0], Predicate::and));
}
public static <T> Stream<T> filter(Stream<T> source, Predicate<T> predicate) {
    return source.filter(predicate);
}
Run Code Online (Sandbox Code Playgroud)

这将是一个可接受的解决方案,因为它不需要在呼叫方面进行任何更改,同时同时提高单arg情况的效率.


请注意,您的varargs方法允许零参数,但如果以这种方式调用则会失败.所以你应该添加另一个重载:

public static <T> Stream<T> filter(Stream<T> source) {
    return source;
}
Run Code Online (Sandbox Code Playgroud)

或者使方法对零参数情况安全:

@SafeVarargs
public static <T> Stream<T> filter(Stream<T> source, Predicate<T>... predicates) {
    return Arrays.stream(predicates).reduce(Predicate::and)
                 .map(source::filter).orElse(source);
}
Run Code Online (Sandbox Code Playgroud)