0

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:

  1. Initialize letterType on first use (within the if)
  2. Initialize letterType by assigning it null

    /*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?

Dan
  • 448
  • 7
  • 18
  • Return right away and throw an exception if not found. Returning a default value is then the only other option, whether it's `null` or something else. – Sotirios Delimanolis May 11 '16 at 02:11
  • 2
    You have to decide what you want your code to do if the `String` doesn't match any of the constants. Throw? Return null? We can't tell you, there's no universal rule. This is a decision you have to make. – Louis Wasserman May 11 '16 at 02:14
  • The problem has nothing to do with initialization or instantiation; those are just syntactical technicalities. The real question is what you want to do in the default case, i.e. where there is no match. Once you've solved that problem, there are a number of ways to formulate your code. On a related note, your method is awfully similar to `SomeEnum.valueOf(String)`. – shmosel May 11 '16 at 02:21

0 Answers0