28

Background

I am getting this error message three times:

Enum value used in 'when expression' should be unqualified

In relation to this code:

Schema.DisplayType fieldType = getType(fieldName);

switch on fieldType {
    when Schema.DisplayType.STRING {  // this line errors
        // do stuff
    }
    when Schema.DisplayType.CURRENCY { // this line errors
        // do stuff
    }
    when Schema.DisplayType.DOUBLE { // this line errors
        // do stuff
    }
    when else {
        throw new CustomException('Unknown field type: ' + fieldType);
    }
} 

Questions

  1. Why am I getting the error?
  2. How do I fix it?

1 Answer 1

49

You need to take the namespace and enclosing class qualifiers off of the enum values. It knows what you mean because it know the type of the value you are switching on. So, you need to write it like this:

Schema.DisplayType fieldType = getType(fieldName);

switch on fieldType {
    when STRING {
        // do stuff
    }
    when CURRENCY { 
        // do stuff
    }
    when DOUBLE { 
        // do stuff
    }
    when else {
        throw new CustomException('Unknown field type: ' + fieldType);
    }
} 
1
  • 1
    I really needed this lol.
    – Soji
    Commented Jul 31, 2021 at 4:40

You must log in to answer this question.

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