1

In a few places I have code of this nature:

private static void myMethod(SObjectType t) {
    if (t == Claim__c.SObjectType) xyzForClaims();
    else if (t == Account.SObjectType) xyzForAccounts();
    else if (t == Contact.SObjectType) xyzForContacts();
    ...
}

for a great many SObjectTypes. It's a bit ugly, and if called a lot all the if/else if tests could become expensive.

It would be great if this was supported:

private static void myMethod(SObjectType t) {
    switch on t {
        case Claim__c.SObjectType { xyzForClaims(); }
        case Account.SObjectType { xyzForAccounts(); }
        case Contact.SObjectType { xyzForContacts(); }
        ...
    }
}

but it isn't. The nearest thing I can think of (short of refactoring into multiple classes) is:

private static void myMethod(SObjectType t) {
    switch on String.valueOf(t) {
        case 'Claim__c' { xyzForClaims(); }
        case 'Account' { xyzForAccounts(); }
        case 'Contact' { xyzForContacts(); }
        ...
    }
}

Am I missing a better approach here?

0

1 Answer 1

3

The alternative solution (for now) would be:

static void myMethod(SObjectType t) {
  switch on t.newSobject() {
    when Claim__c claim { xyzForClaims(); }
    when Account account { xyzForAccounts(); }
    when Contact contact { xyzForContacts(); }
    ...
  }
}

It is possible that the sObjectType (and others) will be supported in the future, so make sure you check the release notes in the future. Also see this related question.

5
  • Yeah sneaky. But seems so wrong...
    – Keith C
    Commented Jun 18, 2019 at 17:59
  • @KeithC I agree, it'd be nice to have sObjectType as a native supported type. It was said that the initial release of switch was to "get something out there" and that future releases may support more types (obviously, safe harbor, yada, yada). I'd use this method for now, as I feel it would be the easiest to convert to supporting sObjectType directly if that ever gets released.
    – sfdcfox
    Commented Jun 18, 2019 at 18:03
  • Good point. Don't want to lose the compile time checking. And thanks for the performance info on the earlier question; I would have assumed more cost so good to know.
    – Keith C
    Commented Jun 18, 2019 at 18:05
  • 1
    Just checked that the variable e.g. claim can't be left out but the same name e.g. x or sob can be used for each case which reads better when that variable isn't used.
    – Keith C
    Commented Jun 19, 2019 at 8:26
  • @KeithC I never tried using the same name. That's a good thing to know.
    – sfdcfox
    Commented Jun 19, 2019 at 12:53

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