尝试使用 java-1.21.0-openjdk-amd64 编译以下代码会导致这些错误
.../TransactionProfile.java:[60,22] variable emvData might already have been assigned
.../TransactionProfile.java:[61,21] variable emvData might already have been assigned
.../TransactionProfile.java:[63,3] variable emvData might not have been initialized
public abstract class TransactionProfile {
protected DeviceContext context;
protected PeripheralResponse response;
protected final PeripheralMessage emvData;
protected final transient PeripheralTags peripheralTags = PeripheralTags.getInstance();
TransactionProfile(DeviceContext context, PeripheralResponse response) {
this.context = context;
this.response = response;
if (response == null) {
emvData = new PeripheralMessage(new LinkedHashMap<>());
} else {
response.get(peripheralTags.emvDataTag)
.ifPresentOrElse(
emv -> emvData = new PeripheralMessage(emv.getUniqueMapOfChildren()),
() -> emvData = new PeripheralMessage(new LinkedHashMap<>()));
}
}
当构造函数不含 lambda 时,它可以正常编译
TransactionProfile(DeviceContext context, PeripheralResponse response) {
this.context = context;
this.response = response;
Tlv emv = null;
if (response != null) {
emv = response.get(peripheralTags.emvDataTag).orElse(null);
}
if (emv == null) {
emvData = new PeripheralMessage(new LinkedHashMap<>());
} else {
emvData = new PeripheralMessage(emv.getUniqueMapOfChildren());
}
}
emvData 如何在第二种形式而不是第一种形式中“明确分配”?据我所知,别无选择。 https://docs.oracle.com/javase/specs/jls/se15/html/jls-16.html
直观的答案是Java编译器不理解ifPresentOrElse
方法的
语义。它不知道这两个 lambda 中的一个或另一个将被执行。
技术答案是,JLS第 16 章中的明确赋值规则并没有说变量 >isprove< definitely assigned in your example. The fact that you could probably 会发生赋值(假设 ifPresentOrElse
符合 javadoc),这不是重点。