1

I have 2 enums with same values in them and some methods that use one enum and some methods that use the other. I want to pass one of the enum types in place of the other. For example:

public enum Colors { RED, BLUE, GREEN }

public enum ScreenColors { RED, BLUE, GREEN }

public void myFunc(Colors color) {
    // Some code
}

// Want to call this as:
myFunc(ScreenColors.RED);
ayushgp
  • 4,891
  • 8
  • 40
  • 75
  • so, indeed you need to implement some mapping between them. since you already guessed that, what is the problem you are having? – Stultuske Jan 29 '18 at 13:37
  • @Stultuske any other way than creating a mapping? I have 3 such pairs. Will have maybe more in the future. – ayushgp Jan 29 '18 at 13:39
  • the two types look similar, but syntactically, they don't match. Unless, maybe, you didn't use the enums in that myFunc method, but enum.name() or something similar. – Stultuske Jan 29 '18 at 13:40
  • I'm needing to do this because one of the enums reside in an external library and I dont want all my codebase to be dependent on it. And I'm not using the string representation inside the method either. The one you suggested is kind of bad to have everywhere in the code IMO: `Colors.valueof(ScreenColors.RED.toString())` – ayushgp Jan 29 '18 at 13:45
  • when did I ever suggest that? either way, either you use RED.name() (or similar), or you use mapping, or you duplicate code. but it is a quite simple truth that ScreenColors and Colors are not of the same type. – Stultuske Jan 29 '18 at 13:48
  • You suggested using enum.name() which is almost same as toString()(https://stackoverflow.com/questions/18031125/what-is-the-difference-between-enum-name-and-enum-tostring) – ayushgp Jan 29 '18 at 13:51
  • yes, but not for that purpose. – Stultuske Jan 29 '18 at 13:52

1 Answers1

4

you can add this static bloc to colors enum

private static final Map<Colors, ScreenColors> LOOK_UP = new HashMap<>();

static {
    for (Colors value : EnumSet.allOf(Colors.class)) {
        LOOK_UP.put(value, ScreenColors.valueOf(value.name());
    }
}

public static ScreenColors forColors(Colors color) {
    return LOOK_UP.get(color);
}

then you can call

myFunc(Colors.forColors(ScreenColors.RED));
andolsi zied
  • 3,553
  • 2
  • 32
  • 43
  • a possibility, but a risky one. This implies that if one of the enums ever gets a new Color, so MUST the other, which may not always be the case. – Stultuske Jan 29 '18 at 13:51