Static analysis of exhaustive switch statements of enums [duplicate]

孤人 提交于 2019-12-11 04:15:26

问题


Consider the following code:

enum MyEnum {
  A, B, C;
}

int foo(MyEnum e) {
  switch (e) {
    case A:
      return 1;
    case B:
      return 2;
    case C:
      return 3;
  }
}
^ error: missing return statement

The compiler does not like this. Contrast this example with:

int bar() {
  if (...) {
    return 1;
  } else {
    return 2;
  }
}

The issue with the switch could be addressed with a default case, but you could argue that's unneeded here. All of the enum values are covered in the cases of the switch. Does static analysis of the switch statement know that, with returns in an exhaustive switch, the code block after the switch statement is unreachable?

I tried looking at the language spec, but I didn't see this point clearly addressed.


回答1:


Well, Java does not implement enums natively as other languages like C/C++ or .NET. They are just instances of a (final) class. So in fact your operator == compares for reference equality rather than integer values as you might have suggested.

This is the reason, why the switch statement is not complete. The reference might just be null.

Furthermore you might have defined your own enum class with a public constructor which might create any arbitrary number of instances.


By the way: the by far easiest way to implement your foo method is

int foo(MyEnum e)
{ return e.ordinal() + 1;
}

But note that .ordinal() does not return any value associated with your enum constant. It is just the index in order of definition.



来源:https://stackoverflow.com/questions/50607799/static-analysis-of-exhaustive-switch-statements-of-enums

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!