2

I would except the following code to work but I get the following error:

null occurs as more than one when branch for this switch statement

Any thought why?

BTW, if I add the value in the when as a string literal it works.

Found the same issue somewhere else.

private static String A = 'a';
private static final String B = 'b';
private final String C = 'c';

switch on obj.field__c {  
    when 'A'{ //This works
        callClassA();
    }
    when B{
        callClass(B);
    }
    when C{
        callClassC();
    }
    when else {
        continue;
    }
}

1 Answer 1

6

You can only use explicit string literals (no variables) in when blocks here. Note the documentation explicitly states a literal value must be used:

When Blocks

Each when block has a value that the expression is matched against. These values can take one of the following forms.

  • when literal {} (a when block can have multiple, comma-separated literal clauses)
  • when SObjectType identifier {}
  • when enum_value {}

The value null is a legal value for all types.

Each when value must be unique. For example, you can use the literal x only in one when block clause. A when block is matched one time at most.

You must log in to answer this question.

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