[SalesForce] Illegal assignment from SObject to Contact

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.

Contact conToUpdate = (Contact)sObjectUpdater.getSObject(con.Id);

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 of sObject). You can perform a cast to tell the compiler that the sObject instance you're getting back from getSObject() is actually a Contact; if at runtime this is not the case (i.e., you get back an Account or something else that isn't a Contact), 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.

Related Topic