在Java中通过lambda返回值

Fre*_*man 10 java lambda runnable

直到现在我设法找到我需要的所有答案,但这个令我困惑.假设我们有示例代码:

public class Animal {
   private String species;
   private boolean canHop;
   private boolean canSwim;
   public Animal(String speciesName, boolean hopper, boolean swimmer) {
     species = speciesName;
     canHop = hopper;
     canSwim = swimmer;
   }
  public boolean canHop() { return canHop; }
  public boolean canSwim() { return canSwim; }
  public String toString() { return species; }
}

public interface CheckAnimal {
   public boolean test(Animal a);
}

public class FindSameAnimals {
   private static void print(Animal animal, CheckAnimal trait) {
      if(trait.test(animal)){
         System.out.println(animal);
      }

   public static void main(String[] args) {
      print(new Animal("fish", false, true), a -> a.canHop());
   }
}
Run Code Online (Sandbox Code Playgroud)

OCA学习指南(考试1Z0-808)一书中说这两行是等价的:

a -> a.canHop()
(Animal a) -> { return a.canHop(); }
Run Code Online (Sandbox Code Playgroud)

这是否意味着,在幕后,Java 在第一种情况下添加关键字返回代码?

如果回答是YES,则下一代码如何编译(想象其他所有内容都在适当的位置):

static int counter = 0;
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(() -> counter++));
Run Code Online (Sandbox Code Playgroud)

如果我们知道执行和Runnable 运行的签名是:

void execute(Runnable command)
void run()
Run Code Online (Sandbox Code Playgroud)

如果答案为否,则Java如何知道何时需要返回某些内容以及何时不返回?也许在

a -> a.canHop()
Run Code Online (Sandbox Code Playgroud)

我们想要忽略boolean返回类型的方法.

Pet*_*rey 12

这是否意味着,在幕后,Java在第一种情况下添加关键字返回代码?

不,编译器生成字节代码,它可能生成相同的字节代码,但它不会更改语法,然后再次编译它.

我们想忽略布尔返回类型的方法.

它可以根据所考虑的功能接口忽略一个值.

a -> a.canHop()
Run Code Online (Sandbox Code Playgroud)

可能

(Animal a) -> { return a.canHop(); }
Run Code Online (Sandbox Code Playgroud)

要么

(Animal a) -> { a.canHop(); }
Run Code Online (Sandbox Code Playgroud)

基于背景,但如果可能的话,它有利于第一个.

考虑ExecutorService.submit(Callable<T>)ExecutorService.submit(Runnable)

ExecutorService es = Executors.newSingleThreadExecutor();
es.execute(() -> counter++); // has to be Runnable
es.submit(() -> counter++); // Callable<Integer> or Runnable?
Run Code Online (Sandbox Code Playgroud)

保存返回类型,你可以看到它是一个 Callable<Integer>

final Future<Integer> submit = es.submit(() -> counter++);
Run Code Online (Sandbox Code Playgroud)

试试自己,这是一个较长的例子.

static int counter = 0;

public static void main(String[] args) throws ExecutionException, InterruptedException {
    ExecutorService es = Executors.newSingleThreadExecutor();

    // execute only takes Runnable
    es.execute(() -> counter++);

    // force the lambda to be Runnable
    final Future<?> submit = es.submit((Runnable) () -> counter++);
    System.out.println(submit.get());

    // returns a value so it's a Callable<Integer>
    final Future<Integer> submit2 = es.submit(() -> counter++);
    System.out.println(submit2.get());

    // returns nothing so it must be Runnable
    final Future<?> submit3 = es.submit(() -> System.out.println("counter: " + counter));
    System.out.println(submit3.get());

    es.shutdown();
}
Run Code Online (Sandbox Code Playgroud)

版画

null
2
counter: 3
null
Run Code Online (Sandbox Code Playgroud)

第一次submit采取Runnable这样Future.get()的回报null

第二submit默认为是一个Callable这样Future.get()的回报2

第三submit只能是一个void返回值,所以它必须是一个Runnable这样Future.get()的回报null


Sam*_*s33 6

您对声明的范围感到困惑return。该return语句(无论是由编译器作为字节码插入还是由程序员作为源代码插入)从 lambda 返回,而不是从调用 lambda 的方法返回。

void foo() {
    Supplier<String> 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");
}
Run Code Online (Sandbox Code Playgroud)


Gui*_*sel 6

是的,当仅指定单个语句时,它的值会自动从 lambda 返回。

那么,由于Runnable是函数式接口,因此可以将其定义为 lambda。返回类型为void,因此 lambda 内的任何返回值都将被忽略。