Mark generic parameter type as functional interface in Java 8

I want to restrict a function type parameter to a functional interface.

Something like that:

public static <@FunctionalInterface T extends Function<A, B>> T foo () {
    return a -> bar;
}

@FunctionalInterface not allowed here.

The goal is to enable the return of a lambda with a type parameter type. Since it Tcan be a normal class, lambda return is not allowed.

Is it possible to limit the type parameter to a functional interface?

+4
source share
2 answers

, . , .

public static <@FunctionalInterface T extends Function<A, B>> T foo() {
    return a -> bar;
}

, , , T, foo(), foo() foo(). .

, Erasure. foo(), . , T.

, , , . . new -.


, - , , , "". , factory, :

public static <A,B> Function<A,B> getter(Map<?, ? extends B> map) {
    return a->map.get(a);
}

A B Map, Map.get A, , - B, ? extends B, B.

, Function, X,

interface X extends Function<String, Integer> {}

factory X, , :

Map<String, Integer> map=new HashMap<>();
X x=getter(map)::apply;
x.apply("foo");

X, , .

+6

-fu , , :

public static <T, R> Function<T, R> foo() {
    // ...
}

, R, T. R, new R() .

, , T R, Map:

public static <K, R, T extends Map<K,R>> Function<T, R> makeGetter(K key) {
    return a -> a.get(key);
}

, , :

import java.util.function.Function;
import java.util.*;
public class Example {

    public static final void main(String[] args) {
        Map<String,Character> mapLower = new HashMap<String,Character>();
        mapLower.put("alpha", 'a');
        mapLower.put("beta",  'b');

        Map<String,Character> mapUpper = new HashMap<String,Character>();
        mapUpper.put("alpha", 'A');
        mapUpper.put("beta",  'B');

        Function<Map<String, Character>, Character> getAlpha = makeGetter("alpha");

        System.out.println("Lower: " + getAlpha.apply(mapLower));
        System.out.println("Upper: " + getAlpha.apply(mapUpper));
    }

    public static <K, R, T extends Map<K,R>> Function<T, R> makeGetter(K key) {
        return a -> a.get(key);
    }
}

:

Lower: a
Upper: A

, , .

+2

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


All Articles