Why can we not use default methods in lambda expressions?

前端 未结 5 1830
既然无缘
既然无缘 2020-12-24 01:25

I was reading this tutorial on Java 8 where the writer showed the code:

interface Formula {
    double calculate(int a);

    default double sqrt(int a) {
           


        
5条回答
  •  攒了一身酷
    2020-12-24 01:40

    Lambda expressions work in a completely different way from anonymous classes in that this represents the same thing that it would in the scope surrounding the expression.

    For example, this compiles

    class Main {
    
        public static void main(String[] args) {
            new Main().foo();
        }
    
        void foo() {
            System.out.println(this);
            Runnable r = () -> {
                System.out.println(this);
            };
            r.run();
        }
    }
    

    and it prints something like

    Main@f6f4d33
    Main@f6f4d33
    

    In other words this is a Main, rather than the object created by the lambda expression.

    So you cannot use sqrt in your lambda expression because the type of the this reference is not Formula, or a subtype, and it does not have a sqrt method.

    Formula is a functional interface though, and the code

    Formula f = a -> a;
    

    compiles and runs for me without any problem.

    Although you cannot use a lambda expression for this, you can do it using an anonymous class, like this:

    Formula f = new Formula() { 
        @Override 
        public double calculate(int a) { 
            return sqrt(a * 100); 
        }
    };
    

提交回复
热议问题