function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
quietopusquietopus 

sObject Collection Casting: Documentation Incorrect?

In the Force.com Apex Code Developer's Guide (Versions 18.0 and 19.0), the section on Collection Casting (p. 113 in 18.0 or p. 115 in 19.0) says the following:

 

"Note: Maps behave in the same way as lists with regards to the value side of the Map-if the value side of map A can be cast to the value side of map B, and they have the same key type, then map A can be cast to map B. A runtime error results if the casting is not valid with the particular map at runtime."

 

However,

 

 

// Create an sObject List
List<sOBject> objList = new List<Contact>();

// Cast the sObject List to a Contact List....
List<Contact> conList = (List<Contact>)objList;

// No Exception is thrown here.

// Create an sObject Map
Map<Id,sObject> objMap = new Map<Id,sObject>();

// Cast the sObject Map to a Contact Map...
Map<Id,Contact> conMap = (Map<Id,Contact>)objMap;

// System.TypeException: Invalid conversion from 
// runtime type Map<Id,sObject> tot Map<Id,Contact>

 

Have I missed something?

 

I know that I can construct the Contact map from scratch, casting each sObject element individually, but I would prefer a way to avaoid eating 2*n script statements for a single (supposedly legal) Collection cast.

 

Is this possible?

 

Note that changing the key type from Id to String does not eliminate the Exception.

 

naore.azenkut1.388062734833066E12naore.azenkut1.388062734833066E12
Hi,
There is no way to cast  (Map<Id,opportunity>)objMap, But there is a work around, If we change the values from an Sobject to a list of sobject's the runtime conversion will work:
// This is OK:
map <string,list<Sobject>> sobjMap = new map <string,list<sobject>> ();
map <string,list<opportunity>> oppMap = (map <string,list<opportunity>> ) mObje;

Naore