Returns a common functional interface in Java 8

I want to write a factory function. This should be a function that is called once when different strategies are parameters. It should return a function that selects one of these strategies depending on the parameter that must be executed by the predicate. Well, better look condition3for a better understanding. The problem is that it does not compile. I think, because the compiler cannot understand that a functional interface Hcan be implemented by an implementation. Without generics, it works fine.

@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 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);
    }
}

So what's the problem? Can I solve it, and if possible with Java: how?

+4
1

, :

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

Lambdas interface . H .

, Finder<P, Q>, , , H extends Finder<P, Q>.

- 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 HImpl , ?

+5

Source: https://habr.com/ru/post/1545677/


All Articles