If you open up the details of the error message, it probably says Invalid conversion from runtime type Map<Id, SObject> to Map<Id, Segment__c> Class
. You can't convert Maps with a different type specialization, even if the changed types are convertible. In the particular case of converting a Map<Id, sObject>
to a Map<Id, Specific_SObject__c>
where the key is the Id
of the sObject
value, you could do this by taking advantage of the List
constructor for Map
:
Map<Id, Segment__c> noLockedRecordsMap = new Map<Id, Segment__c>(
(List<Segment__c>)new LockedRecordHandler().removeLockedRecords(newMap).values()
);
In all other cases, you should loop through the map and put its key-value pairs in a new map:
Map<Id, Segment__c> noLockedRecordsMap = new Map<Id, Segment__c>();
Map<Id, SObject> lockedRecordsSObject = new LockedRecordHandler().removeLockedRecords(newMap);
for(Id key : lockedRecordsSObject.keySet())
{
noLockedRecordsMap.put(key, (Segment__c)lockedRecordsSObject.get(key));
}
This could probably also be done by doing round-trip JSON, but the only advantage to that is saving lines of code, most likely it won't be faster. Hopefully in the future Apex will support methods with generic arguments so that it can return a map of the correct type and this won't be necessary.
SObject
.