[英]Why if-else if-else (within a loop) in method gives “return statement missing” while all if-else branches have a return statement?
为什么编译器给我“ return statement missing”错误?
所有可能的条件分支(if-else)都包含一个return语句。
但是,如果我单独拥有相同的if-else-if-else构造(不在for()循环内)-它可以很好地编译,而不会产生此“ return statement missing” erorr吗?
public Resume get(String uuid) {
// compiler shall know that array is not empty!
final Resume[] storage = new Resume[100]; // same for static final
// is executed at least once - see above!
for(Resume resume : storage) {
if (resume == null) {
return null;
} else if (resume.uuid.equals(uuid)){
return resume;
} else {
return null;
}
}
// return statement is missing !!!
}
我能理解编译器-担心如果名为storage的数组为空,则循环将永远不会执行。 为什么编译器会忽略数组的大小? 但这只是高级for循环问题的一半。
让我们进行一个常规的for循环,它完全独立于存储阵列的大小。
public Resume get(String uuid) {
Resume resume = new Resume();
// being a static final field produces same compile error...
final int LIMIT = 100;
// LIMIT is known to compiler, since it is final primitive.
// for loop execution not dependent on storage array being empty
for (int i = 0; i < LIMIT; i++) {
if (resume == null) {
return null;
} else if (resume.uuid.equals(uuid)){
return resume;
} else {
return null;
}
}
// return null; //statement is missing !!!; //
}
是什么解释了第二个for循环问题?
PS我认为这是因为诸如“ i <LIMIT”(即使LIMIT是最终的)之类的东西在编译期间不会评估为true,true仅在运行时出现 ,因此在编译时 ,编译器担心只是在这种情况下;)
即使您为storage
变量分配了一个非空数组,编译器在考虑所有执行路径是否都具有return语句时也没有考虑到这一点。
就编译器而言,for循环可能有0次迭代,因此循环后必须有一个return语句。
实际上,即使在循环条件中仅使用常量,编译器在循环之后仍将需要return语句。 以下方法不会通过编译:
public static int test()
{
for (int i = 0; i < 5; i++) {
return 3;
}
}
如果您的storage
为空,您将永远不会进入循环,因此您将无法获得任何return
语句。
在编译时,您不能保证您的集合永远不会为空,因此编译器需要此执行分支的return语句。
如果storage
为空,则不会发生退货。
所有可能的条件分支都在for循环中,如果您的存储数组为空而不是return语句,该怎么办呢,这就是编译器给您此错误的原因
像这样更改代码,因为如果storage
为空,则传递for
:
public Resume get(String uuid) {
// compiler shall know that array is not empty!
final Resume[] storage = new Resume[100]; // same for static final
// is executed at least once - see above!
for(Resume resume : storage) {
if (resume == null) {
return null;
} else if (resume.uuid.equals(uuid)){
return resume;
} else {
return null;
}
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.