2

Apex is supposed to be based on Java which supports factory method in enums types.

global enum CheckResult {
    PENDING, PASSED, FAILED;

    public static CheckResult fromResult(Boolean aBoolean) {
        if (aBoolean) {
            return PASSED;
        } else {
            return FAILED;
        }
    }
}

I cannot find a form that actually compiles, is this a supported feature in apex, if so how is it achieved in apex?

0

1 Answer 1

4

Apex does support enum's, syntax is bit different than java though.

Proper class based on your example would be as:

public class CheckResult {
    public Enum Result { PENDING, PASSED, FAILED}

    public static Result fromResult(Boolean aBoolean) {
        if (aBoolean) {
            return Result.PASSED;
        } else {
            return Result.FAILED;
        }
    }
}

You could verify the result from execute anonymous from developer console:

CheckResult.Result result = CheckResult.fromResult(true);
// this would be equal to enum value passed
System.debug(result == CheckResult.Result.PASSED);
4
  • 1
    That is great, I have several external checks to be made via REST that returns true or false results via JSON, each exist in salesforce as pending when the record is created but passed/failed as the process completes Your method will work perfectly since I wanted to avoid the conditional testing all over the code base. May 28, 2019 at 15:04
  • 1
    simplest code: return aBoolean ? Result.PASSED : Result.FAILED;
    – cropredy
    May 29, 2019 at 1:17
  • 2
    @cropredy I value clarity over brevity May 29, 2019 at 10:24
  • 1
    @MartinofHessle - perfectly understandable. I was like you when I started with Apex but over time certain idioms became natural and I learned to value terseness (fewer lines).
    – cropredy
    May 29, 2019 at 13:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .