gpt4 book ai didi

java - 有效的最终/最终限制不是没用吗?

转载 作者:行者123 更新时间:2023-12-01 14:07:55 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Variable used in lambda expression should be final or effectively final

(7 个回答)


3年前关闭。




我不明白为什么 java 语言的实现者会这样做,以便在 lambda 中使用并从函数作用域传递到那里的变量必须是最终的。

我反编译了这段代码:

public class Main {
@FunctionalInterface
interface Test {
void method(int t);
}

static void test(Test t) {
t.method(3);
}

public static void main(String... args) {
int a = 3;
test((i)-> {
System.out.println(a + i);
});
}
}

编译器所做的是复制该变量,就像它是通过构造函数传递一样。我得到了这 3 个类:

1:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

import Main.1;
import Main.Test;

public class Main {
public Main() {
}

static void test(Test var0) {
var0.method(3);
}

public static void main(String... var0) {
byte var1 = 3;
test(new 1(var1));
}
}

2:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

import Main.Test;

final class Main$1 implements Test {
Main$1(int var1) {
this.val$a = var1;
}

public void method(int var1) {
System.out.println(this.val$a + var1);
}
}

3:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

@FunctionalInterface
interface Main$Test {
void method(int var1);
}

为什么实现者不能只复制变量而不管它是否被修改,所以我们可以这样做:
public class Main {
@FunctionalInterface
interface Test {
void method(int t);
}

static void test(Test t) {
t.method(3);
}

public static void main(String... args) {
int a = 3;
test((i)-> {
a += 1; // allow modification, a is copied anyway, why not?
System.out.println(a + i);
});
}
}

最佳答案

这没有技术原因。只是如果您允许在 lambda 中使用非最终字段,那么您可以编写看起来不错但实际上不起作用的代码。

例如:

void printSum(Collection<Integer> numbers) {
int sum = 0;
numbers.forEach(i -> sum += i);
System.out.println(sum);
}

目前编译器不会让你这样做,因为你不能访问非最终 sum在 lambda 内部。正如您所指出的,该变量无论如何都会被复制到 lambda 中,因此它可以允许这样做。

如果是,那么这段代码会编译,但总是打印 0,因为只有 sum lambda 内的 -copy 被修改而不是“真实的”。

只允许引用“有效最终”变量是不需要 final 的一个很好的折衷方案。关键字无处不在,同时仍然避免这样的误解。

关于java - 有效的最终/最终限制不是没用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50529318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com