I am getting the following error:
Illegal assignment from SObject to Contact
I created a class called DynamicSObjectUpdater that I use to consolidate DML statements in my triggers. Basically you just call the class getSObject
and it appends the SObject to a Map called sorToUpdate
and then returns the SObject.
In one of my classes, I am calling the Class and its saying the following code is an illegal assignment from SObject to Contact.
Contact conToUpdate = sObjectUpdater.getSObject(con.Id);
I am not sure what I am missing here to make this work.
public with sharing class DyanmicSObjectUpdater {
Map<SObjectType, Map<Id, sObject>> sorToUpdate = new Map<SObjectType, Map<Id, sObject>>();
public SObject getSObject(ID sObjectID)
{
SObjectType sot = sObjectID.getSobjectType();
if(!sorToUpdate.containsKey(sot))
{
sorToUpdate.put(sot, new Map<Id, SObject>());
}
SObject targetSObject = sorToUpdate.get(sot).get(sObjectID);
if(targetSObject == null)
{
targetSObject = sObjectID.getSobjectType().newSobject(sObjectID);
sorToUpdate.get(sot).put(sObjectID, targetSObject);
}
return targetSObject;
}
public void updateSObjects()
{
List<SObject> sObjectsToUpdate = new List<SObject>();
if(sObjectsToUpdate.size() > 0)
{
for(SObjectType sorType: sorToUpdate.keySet())
{
sObjectsToUpdate.addAll(sorToUpdate.get(sorType).values());
}
}
if(sObjectsToUpdate.size()>0) update sObjectsToUpdate;
}
}
Best Answer
You need to cast the return value.
More generally, you cannot directly assign a value typed at compile time as a superclass (like
sObject
) to a variable typed as a subclass (Contact
is a subclass ofsObject
). You can perform a cast to tell the compiler that thesObject
instance you're getting back fromgetSObject()
is actually aContact
; if at runtime this is not the case (i.e., you get back anAccount
or something else that isn't aContact
), you will receive an exception.You might find the implementation of the Unit of Work pattern in
fflib
interesting as you're building this type of generic/abstracted DML code.