繁体   English   中英

返回Java 8中的通用功能接口

[英]Return generic functional interface in Java 8

我想写一些功能工厂。 它应该是一个函数,它被称为一次不同的策略作为参数。 它应该返回一个函数,该函数根据参数选择其中一个策略,该参数由谓词实现。 那么,更好地了解condition3以便更好地理解。 问题是,它没有编译。 我认为因为编译器无法弄清楚,功能接口H可以通过实现来实现。 没有泛型它工作正常。

@FunctionalInterface
public interface Finder<T, S> {

    Stream<S> findBest (T t);

    // Valid code
    static <P, Q> Finder<P, Q> condition1 () {
        return p -> null;
    }

    // Valid code, but selects just one of the H's when the method is invoked
    static <P, Q, H extends Finder<P, Q>> H condition2 (Pair<Predicate<P>, H>... hs) {
        return hs[0].getRight ();
    }

    // Should return a method, which selects the appropiate H 
    // whenever it is invoked with an P
    // Compiler complain: 
    // The target type of this expression must be a functional interface
    static <P, Q, H extends Finder<P, Q>> H condition3 (Pair<Predicate<P>, H>... hs) {
        return p -> stream (hs).filter (pair -> pair.getLeft ().test (p))
                               .findFirst ()
                               .map (Pair::getRight)
                               .map (h -> h.findBest (p))
                               .orElseGet (Stream::empty);
    }
}

那么这里的问题是什么? 我可以解决它,如果可以用Java:怎么做?

查看方法的签名并尝试告诉确切的返回类型:

static <P, Q, H extends Finder<P, Q>> H condition3(…

Lambdas只能在编译时实现已知的interface 但编译器不知道H的实际类型参数。

你的第一种方法是有效的,因为它返回了lambda可以实现的类型Finder<P, Q> ,你的第二种方法是有效的,因为它不使用lambda来实现返回类型H extends Finder<P, Q>

只有第三种方法尝试为类型参数指定lambda表达式H extends Finder<P, Q>


解决方案不是让调用者可以自由地强制使用特定子类型的Finder作为方法的返回类型:

static <P, Q, H extends Finder<P, Q>>
    Finder<P, Q> condition3(Pair<Predicate<P>, H>... hs) {

要说明原始方法签名的含义,请查看以下示例:

final class HImpl implements Finder<String,String> {
    public Stream<String> findBest(String t) {
        return null; // just for illustration, we never really use the class
    }
}

...

HImpl x=Finder.<String,String,HImpl>condition3();

鉴于您的原始方法签名,此编译没有任何错误。 但是方法condition3应该如何使用你的lambda表达式提供HImpl的实例呢?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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