Stack Exchange Network
Stack Exchange network consists of 183 Q&A communities including
Stack Overflow
, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
Visit Stack Exchange
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this community
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
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;
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.