I am having trouble comparing an Enum value to a predefined value within a function.
I have an Enum setup as
public enum SomeEnum {
A, B, C
}
Then in another class, I have a method which compares a String to the Enum values, and returns the Enum value if they are equals according to the toString() method of the Enum value.
The Method:
/**
* Example
* @param someString - A string which could be equivalent to an SomeEnum value.
* @return SomeEnum Type
*/
private static ClassA someMethod(String someString) {
SomeEnum letterType; // Problem
for (SomeEnum letter : SomeEnum.values()) {
if (someString.equals(letter.toString())) {
letterType = letter;
}
}
return letterType;
}
The above code gives me an error stating that:
the variable letterType may have not been initialized
Fair enough, just instantiate it!...
SomeEnum letterType = new SomeEnum(); // NO
However Enums (by definition) cannot be instantiated.
This leaves me with 2 options:
- Initialize
letterTypeon first use (within theif) Initialize
letterTypeby assigning itnull/*Options*/ //1. if (someString.equals(letter.toString())){ SomeEnum letterType = letter; } //2. private static ClassA someMethod(String someString) { SomeEnum letterType = null; //... }
Option 1 restricts me returning
letterType as it is now not reachable. Option 2 works, however instantiating with
null seems like it is not good practice - correct me if I am wrong.
Besides using a switch statement and changing the function, it seems I am only able to achieve this using Option 2.
Is there another way to achieve this?/missing something simple..?
Is my understanding of this concept incorrect...?
Should I just be using a switch statement instead?