java enums cannot convert from MyClass.Result to int

I have issues storing an enum value and then querying it via the toString() method. I require to handcode the numbers. How do I safely override my toString() ?

public enum Result {
        SUCCESS(0),
        INVALID_UPLOAD_KEY(-20),
        UPLOAD_KEY_NOT_FOUND(-80);

        private final int value;  //do I need this?

        private Result(int value) {
            this.value = value;
        }

        public static Result fromInt(final int n) {
            for (final Result result : values()) {
                if (result.getValue() == n) {
                    return result;
                }
            }
            return null;
        }


        public int getValue() {
            return this.value;
        }

        public String toString() {
            switch (this.value) {
                case UPLOAD_KEY_NOT_FOUND: //Type mismatch: cannot convert from MyClass.Result to int
                    return "Upload Key not found";
                case INVALID_UPLOAD_KEY: //Type mismatch: cannot convert from MyClass.Result to int
                    return "Invalid Upload Key";
                case SUCCESS: //Type mismatch: cannot convert from MyClass.Result to int
                    return "Success";
                default:
                    return "No result code associated with: " + this.value;
            }
        }
    }

Eclipse complains the toString method

Type mismatch: cannot convert from MyClass.Result to int
Jon Skeet
people
quotationmark

Others have explained why your switch statement is failing - and unless you need the numbers for some other reason, you can get rid of them. But you don't need the switch statement at all - just make the message an instance variable:

public enum Result {
    SUCCESS("Success"),
    INVALID_UPLOAD_KEY("Invalid Upload Key"),
    UPLOAD_KEY_NOT_FOUND("Upload Key not found");

    private final String message;

    private Result(String message) {
        this.message = message;
    }

    @Override public String toString() {
        return message;
    }
}

Of course if you still need the integer value for other reasons, it's fine to keep that as well.

I would be tempted not to override toString(), but to provide a getMessage() method instead, by the way.

people

See more on this question at Stackoverflow