Switch on pseudo enum

Java says I can’t use a switch statement on a pseudo enum (For example entitytypes, itemtypes, etc because a “Constant expression is required”.

Is there a way to fix this or should I use if statements?

EntityTypes is a class not an enum, so you can’t use switch statement.
Just use if statement :smile:

1 Like

Something like that can maybe work:

switch (entityDeathEvent.getEntity().getType().getName()) {                 
                    case "BLAZE":
                        //something
                        break;

Because it’s not valid Java to switch on some arbitrary type.

If you post a code example people will be able to suggest cleaner solutions then “just using ifs”

1 Like

The biggest issue is that Java switch statements require a sort of bounds or “index” if you will. It’s something that in Scala you can solve with matching cases, but in Java, it’s just not doable with the switch mechanics that the compiler performs. Albeit, it’s almost cleaner in bytecode to just use a bunch of if statements for most cases, however, it’s of course an ugly issue. You can read more here: http://stackoverflow.com/questions/338206/why-cant-i-switch-on-a-string the first answer gives a very good explanation on why in Java 7, you can now switch on strings, and then some understanding on how switch statements actually work.

1 Like

So why don’t you just use enums…?

It’s so Sponge can use the same object for SpongeAPI and NMS. For example, TextColors holds Minecraft’s EnumChatFormatting objects, with a mixin to make them inplement TextColor.

1 Like

The exact same can be achieved with an enum, and not only does it provide switch support, it also contains many useful enum methods as well.

1 Like

I didn’t make this decision. Probably best to ask one of the Sponge developers.

Check this one to know more about…Java Enum

Balmer