0

I am trying to cast the type Map<String, SObject> to Map<String, EmailTemplate>, my code as follows:

EmailTemplate emailTemplate = [SELECT Id FROM EmailTemplate LIMIT 1].get(0);

SObject sobj = (SObject) emailTemplate;

Map<String, SObject> sobjectMap = new Map<String, SObject>();

sobjectMap.put('red', sobj);

Map<String, EmailTemplate> emailTemplateByColorMap = (Map<String, EmailTemplate>) sobjectMap;

I am getting the following error message:

Error on line 9, column 1: System.TypeException: Invalid conversion from runtime type Map to Map AnonymousBlock: line 9, column 1

Any idea why is throwing an error message? An SObject can be cast to EmailTemplate. Right?

3

An SObject by itself can be cast to EmailTemplate, however, Map cannot, that happens, because you may have not only EmailTemplate as values in Map, but also other SObjects.

Example:

Map<String, SObject> sobjectMap = new Map<String, SObject>();
sobjectMap.put('red', new Account(Name = '123'));
sobjectMap.put('green', new Contact(LastName = '123'));

So you cannot convert Map, but you can retrieve your email template by key-color and cast it itself:

EmailTemplate redTemplate = (EmailTemplate) sobjectMap.get('red');
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.