I have a problem with a variable that is being initialized inside a switch over an enum. It seems that Android Studio (and Eclipse) is ignoring the fact that I'm initializing the variable in all the cases and stated: "Variable 'x' might not have been initialized". I do not want to put a default case.
Code example:
public enum eTest {
One,
Two
}
public class Test {
public void method(eTest value) {
String toPrint;
switch (value) {
case One:
toPrint = "One";
break;
case Two:
toPrint = "Two";
break;
}
System.out.println(toPrint); // <-- said error
}
}
I do not want to initialize the variable but I'm not sure there is a way to do this without initializing (I'd love to learn I'm wrong). Assuming this is not possible I wanted to make sure that new enum values will have to be added to this switch.
First try:
I've tried adding the "Enum 'switch' statement that misses case" to the Android Studio settings, but that has two issues:
- It does not fail the build (only shows the place with a red marker).
- It depends on the local configuration, and I'd like something that can be enforced on all users.
Second try:
I found that this should be possible with lintOptions in the build.gradle file (I'm using Android Studio, as mentioned), however I could not make it work as desired. I've added the following options to the build.gradle:
lintOptions {
enable 'EnumSwitchStatementWhichMissesCases'
abortOnError true
}
This did not work as well, I'm assuming because of two possible issues:
- The name is wrong (I took it from the xml that Android Studio created when using the settings).
- The default severity of this issue is warning and not error, however I could not find how to change the severity of an issue.
Third try:
It should be possible to add a lint.xml to the Android Studio project, I tried this as well but it did not fail the build, so I'm assuming I did something wrong there. I put the following in the AndroidManifest location:
<?xml version="1.0" encoding="UTF-8"?>
<lint>
<issue id="EnumSwitchStatementWhichMissesCases" severity="error" />
</lint>
Furthermore:
I've seen this answer, but this is not what I'm looking for, and since this is about a specific build process, I hope that there's a better solution.
The question:
Is it possible to:
1. Solve the original problem. edit: this cannot be done (thanks Blackbelt - see comment below)
and if not:
2. Add the said option to the build process (any option that can be enforced on other users is welcome).
Edit: clarification - I would like to know how to prevent enums with missing cases in compile time, using lint in Android Studio