Switch: Enum value used in ‘when expression’ should be unqualified

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?

Answer

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);
    }
} 

Attribution
Source : Link , Question Author : Robs , Answer Author : Aidan

Leave a Comment