I have a function which return a type int. However, I only have a value of the TAX enumeration.
How can I cast the TAX enumeration value to an int?
public enum TAX {
NOTAX(0),SALESTAX(10),IMPORTEDTAX(5);
private int value;
private TAX(int value){
this.value = value;
}
}
TAX var = TAX.NOTAX; // This value will differ
public int getTaxValue()
{
// what do do here?
// return (int)var;
}
A somewhat different approach (at least on Android) is to use the IntDef annotation to combine a set of int constants
Use as function parameter:
or in a variable declaration:
Maybe it's better to use a String representation than an integer, because the String is still valid if values are added to the enum. You can use the enum's name() method to convert the enum value to a String an the enum's valueOf() method to create an enum representation from the String again. The following example shows how to convert the enum value to String and back (ValueType is an enum):
If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.
If you want a unique number that represent the enum value, you can use
ordinal()
.You'd need to make the enum expose
value
somehow, e.g.(I've changed the names to be a bit more conventional and readable, btw.)
This is assuming you want the value assigned in the constructor. If that's not what you want, you'll need to give us more information.
I prefer this:
then: