这是一个示例方法:
boolean method(int value, boolean check1, boolean check2) {
String code;
boolean valueIncorrect = false;
boolean otherIncorrect = false;
if (value < 0 || value > 10) {
code = "lengthCode";
valueIncorrect = true;
}
if (check1) {
code = "otherCode";
otherIncorrect = true;
} else if (check2) {
code = "otherCode";
otherIncorrect = true;
}
if(!valueIncorrect && !otherIncorrect) {
return true;
}
if (otherIncorrect) {
return code.contains("HELLO");
}
return true;
}
当我尝试编译时,我在尝试调用 contains() 方法的行收到错误:
variable code might not have been initialized
。
如果我们看一下逻辑,此时代码不可能为空,对吧?还是我绊倒了?仅当其中一个布尔值为 true 时,执行才会到达该点,并且无论其中任何一个布尔值设置为 true,代码的值也会被设置。
所以我不期望编译器进行无限复杂的分析,但我也知道如果它是一个简单得多的条件:
if(boolean) code = "x";
else code = "y";
return code.contains("whatever");
这样就不会抛出错误。我有什么误解吗?
从技术上讲,你是对的,因为顶部的 if/if/else-if 通过而没有被击中,两者都是 false,并且它将在之前的下一个语句中尽早返回 true。
虽然这是非常间接的,我认为编译器不会推断出类似的东西。