0

I created a very basic enum

public enum StatusCode {

OK(0, "Everything ran correctly"),
ERROR(4, "Fatal Error");

private final int value;
private final String description;

StatusCode(final int value, final String description) {
    this.value = value;
    this.description = description;
}

public int getValue() { return value; }

public String getDescription() { return description; }
}

In my method I'm trying to return a integer

public Integer func() { 
   return StatusCode.OK; // Inside method
 }

ERROR:

Type mismatch: cannot convert from StatusCode to Integer

I know I can do StatusCode.OK.getValue() but it looks weird. How can StatusCode.OK be an integer by default?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

2 Answers2

4

How can StatusCode.OK be an integer by default?

It can't be. It's not an Integer, it's a StatusCode.

And that's better. Anybody can create an Integer, with any value in the range. But you can't create a new StatusCode, so you know that the thing you get is definitely one of [this small number of values].

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
4

Java enums are not C/C++/C# enums. They aren't integers in disguise, they are more like classes in disguise.

(In fact they -are- classes in disguise -- https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html)

Whereas in C# enum { Foo, Bar } would have implicit values Foo = 0 and Bar = 1, this is not true in Java.

Your line StatusCode.OK.getValue() is the right thing to do in Java.