Return value by lambda in Java

后端 未结 3 1908
遥遥无期
遥遥无期 2021-02-13 15:24

Till now I manage to find all answers I need but this one confusing me. Let\'s say we have example code:

public class Animal {
   private String species;
   priv         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 15:45

    You are confused about the scope of the return statement. The return statement (whether inserted as bytecode by the compiler or as source code by the programmer) returns from the lambda, and not from the method that calls the lambda.

    void foo() {
        Supplier s = () -> { return "bar" };
        String s = s.get(); // s is assigned to "bar"
        // Execution continues as the return statement in the lambda only returns from the lambda and not the enclosing method
        System.out.println("This will print");
    }
    

提交回复
热议问题