问题描述
编译器声称 MyClass.parse()
的结尾缺少返回语句。这是代码:
The compiler claims that a return statement is missing at the end of MyClass.parse()
. Here is the code:
package de.hs_rm.safelyovertaken.ble;
import android.support.annotation.NonNull;
import java.util.Arrays;
class MyClass {
@NonNull
static MyClass parse(byte[] encoded) throws MyParseException {
MyEnum myEnum = MyEnum.parse(Arrays.copyOfRange(encoded, 0, 2));
switch (myEnum) {
case A:
return new MyClassA();
case B:
return new MyClassB();
case C:
return new MyClassC();
}
// compile error: "Missing return statement"
// return null; // should never be reached
// throw new AssertionError("Should never be reached");
}
}
enum MyEnum {
A, B, C;
@NonNull
static MyEnum parse(byte[] encoded) throws MyParseException {
MyEnum result = null;
// parse logic here
if (result == null) {
throw new MyParseException();
}
return result;
}
}
class MyParseException extends Exception {
}
class MyClassA extends MyClass {
}
class MyClassB extends MyClass {
}
class MyClassC extends MyClass {
}
编译器正确吗? (Android Studio)
Is the compiler right? (Android Studio)
如果是这样,在什么情况下可以达到该方法的目的?我认为 myEnum
不能为 null
并且所有枚举都包含在switch语句中,无论如何,返回语句都会离开方法。 myEnum
不能为 null
,因为 @NonNull
方法<$如果结果为 null
,则c $ c> MyEnum.parse()会引发异常。
If so, under what circumstances could the end of the method be reached? I think myEnum
cannot be null
and all enum are covered in the switch statement where in any case a return statement will leave the method. myEnum
cannot be null
because the @NonNull
method MyEnum.parse()
throws an exception if the result is null
.
如果没有,您是否会用 return null //标记方法的(希望)不可达结尾//永远不会到达
或抛出 AssertionError
?
If not, would you mark the (hopefully) unreachable end of the method with return null // should never be reached
or throw an AssertionError
?
推荐答案
是的,因为它在编译时不验证枚举的覆盖范围。假设枚举位于另一个二进制文件中,并使用新的常量对其进行了更新。该方法将返回什么?
Yes, because it doesn't verify enum coverage at compile time. Say the enum lived in another binary and it was updated with a new constant. What would the method return?
编译器不够聪明,无法弄清楚(尽管您的IDE可能是)。但这是有争议的,因为打开 null
会导致NPE。
The compiler's not smart enough to figure that out (though your IDE might be). But it's a moot point because switching on null
would result in a NPE.
抛出 AssertionError
很常规。或者,考虑将,而不要使用开关。
Throwing an AssertionError
is pretty conventional. Alternatively, consider embedding conditional logic in the enum constants instead of using a switch.
这篇关于“缺少返回声明”;切换后(枚举)-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!