There is a class of type Enum and I want to make a switch for it, but the constant expression required tells me.

Those. this way works

  if (item.getType() == ItemType.TEXT) { } 

but this does not work

  switch (item.getType()){ case ItemType.TEXT: } 

and so it also works

  switch (item.getType().toString()){ case String.valueOf(ItemType.TEXT): } 

Here is the enum class itself

 public enum ItemType { TEXT,PHOTO,EMPTY; } 
  • I won’t say about enum (I don’t understand why case ItemType.TEXT doesn't work), but the switch with String appeared relatively recently. Probably you have an android of the wrong system. On the other hand, the call String.valueOf(ItemType.TEXT) cannot be called a constant expression . Need to write "TEXT" - Sergey

1 answer 1

Do this:

 switch(item.getType()) { case TEXT: break; case PHOTO: break; case EMPTY: break; } 
  • Before swith if necessary, check one more case separately: if (item.getType() == null) { ... } - Sergey
  • one
    great, it works - Kirill Stoianov