• naore.azenkut1.388062734833066E12
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies

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.