Lambda expression vs method reference implementation details

后端 未结 3 1453
梦如初夏
梦如初夏 2021-01-05 15:43

Given this:

class MyClass {
    static class A {
        public boolean property() {
            return Math.random() < 0.5;
        }
    }

    static L         


        
3条回答
  •  太阳男子
    2021-01-05 16:18

    One case where we can find the difference lambda expression & method reference is using as part of Supplier interface. Lets say we have below static method

    public static  T catchException(Supplier resolver) {
        try {
            T result = resolver.get();
            return  result ;
        } catch (Exception e) {
            System.out.println("Exception");
            return null;
        }
    }
    

    When we call the method using lambda expression as below, code work fine since the lambda expression passed as part of Supplier & executed only when get() method is called where the exception is caught.

    List underlyers=null;
    System.out.println(catchException(()->underlyers.size()));
    

    When we call the method using method reference as below, we get NullPointerExecption before calling the method since the reference is executed before passing in to the supplier. The control does not reach get() method in this case.

    List underlyers=null;
    System.out.println(catchException(underlyers::size));
    

提交回复
热议问题