0

Say I have the following enum definition:

enum SaveResult {
    Saved,
    Failed,
    EncryptionError
}

I then have a function that returns a SaveResult

public SaveResult save() {
  . . .
}

I then have a function that returns a boolean based on the result of the save() function:

public boolean doSomething() {
    SaveResult result = this.save();

    switch (result) {
        case Saved:
            return true;
        case Failed:
            return false;
        case EncryptionError:
            return false;
    }

    // Why am i still required to provide `default` case
    // for the switch or a return call at the end of the
    // function if all cases for the switch have already
    // been covered?
    //
    // The error I'm getting is "Missing return statement".
}
Nathan F.
  • 3,250
  • 3
  • 35
  • 69
  • 1
    Additional enumerators could be added without recompilation of `doSomething()`. – Andy Thomas May 28 '19 at 17:29
  • Note that a `default` case is no longer required for enums when using the [updated switch](https://openjdk.java.net/jeps/354) in Java 12 and later. – Logan May 28 '19 at 17:33
  • The same reason this does not compile: `public boolean test() { if(true) return true; }`. Even if logically there is only one path, the compiler will evaluate the impossible path. – Compass May 28 '19 at 17:34
  • I don’t know how hypothetical your example is, but the `switch` could be replaced with `return result == SaveResult.Saved;`. – VGR May 28 '19 at 18:34

0 Answers0