java8新特性-lambda(类型检查)

1.表达式类型检查

public class App {

    public static void test(MyInterface<String, List> inter) {
        List<String> list = inter.stratey("hello", new ArrayList());
        System.out.println(list);
    }

    public static void main(String[] args) {
        test(new MyInterface<String, List>() {
            @Override
            public List stratey(String s, List list) {
                list.add(s);
                return list;
            }
        });

        test((x, y) -> {
            y.add(x);
            return y;
        });

        MyInterface<String, List> myInterface = (x, y) -> {
            y.add(x);
            return y;
        };
        System.out.println(myInterface.stratey("hello", new ArrayList()));
    }
}

@FunctionalInterface
interface MyInterface<T, R> {
    R stratey(T t, R r);
}

总结:(x, y) -> {...} -->test(param) --> param = MyInterface --> lambda表达式 --> MyInterface类型,这个就是对于lambda表达式的类型检查,MyInterface接口就是lambda表达式的目标类型(target typing)

2.参数类型检查

总结:(x, y) -> MyInterface.strategy(T t, R r) --> MyInterface<String, List> inter --> T == String R == List --> lambda --> (x, y) == strategy(T t, R r) -->x==T==String y==R==List,这就是lambda表达式的参数类型检查

原文地址:https://www.cnblogs.com/freeht/p/13040471.html