简体   繁体   English

具有非最终变量的CompletableFuture.runAsync(()->…

[英]CompletableFuture.runAsync(() ->… with a non-final variable

I have this code that works fine: 我有这段代码可以正常工作:

String name = "Oscar";
CompletableFuture.runAsync(() -> doX(name));

Now I need to add some logic to the name variable: 现在,我需要在name变量中添加一些逻辑:

String name = "Oscar";
if (x){
  name = "Tiger";
}
CompletableFuture.runAsync(() -> doX(name));

But now the compiler complains about Variable used in lambda expression should be final or effectively final 但是现在编译器抱怨Variable used in lambda expression should be final or effectively final

I understand from posts like this one that the name must be final or effectively final, but I wonder if there is a way to write the code differently in order to enable the logic on the name variable 我从类似这样的帖子中了解到name必须是final或有效的final,但是我想知道是否有一种方法可以以不同的方式编写代码以启用name变量的逻辑

The lambda expression needs a final variable. lambda表达式需要一个最终变量。 If the initialization code is complicated enough then define a new final variable. 如果初始化代码足够复杂,则定义一个新的最终变量。

final String fName = name;
CompletableFuture.runAsync(() -> doX(fName));

You can use Conditional Operator , something like this: 您可以使用Conditional Operator ,如下所示:

        boolean condition = true;
        String name = condition ? "Tiger" : "Oscar";
        CompletableFuture.runAsync(() -> System.out.println(name));

Or using if statements: 或使用if语句:

 boolean condition = true;
    final String name;
    if(condition) {
        name = "Tiger";
    }else {
        name = "Oscar";
    }
    CompletableFuture.runAsync(() -> System.out.println(name));

Try to decouple resolver logic from the main flow: 尝试将解析器逻辑与主流分离:

public static void somewhere() {
    // Variable even may be explicitly final
    final String name = resolve(true);
    CompletableFuture.runAsync(() -> doX(name));
}

public String resolve(boolean condition) {
    if (condition)
        return "NameX";

    return "NameY";

    // Or:
    // return condition ? "NameX" : "NameY";
}

The advantage of the approach that you may add more complex conditions and can change this logic later without touching the original flow. 这种方法的优点是您可以添加更复杂的条件,并且可以在以后更改此逻辑而不会影响原始流程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM