jmahmood / Underscore.sfdc

An experiment to see how much of underscore.js one could apply to Salesforce Apex.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Casting from List<Object> is a pain in the rear.

jmahmood opened this issue · comments

When we return something like List, it is impossible to just cast it back (say, to List).

The system should use the same "Type" pass-in that is in Pluck in more places. Even if this is not strictly necessary, it would be far easier.

For example, here is a categorization methodology I have in some production code (with some small changes).

class EquipmentMap extends US.PartitionInterfaceAbstract {
	public override String partitionFn(SObject obj){
		return Stock_Calculation_Helper.GetEquipmentQuantityKey(
			(String) obj.get('field1__c'),
			(String) obj.get('field2__c'),
			(String) obj.get('field3__c'),
			(String) obj.get('field4__c')
		);
	}
}

CategorizedEquipment = Equipment_us.rewind().groupby(new EquipmentMap());

This creates a Map<String, Object> but we cannot actually re-cast this to Map<String, List<Equipment__c>> even if we wanted to.

What would be good would be if we added the Type to the constructor of the PartitionInterfaceAbstract class. This could be overridden at the child class level, and then we could initialize using the Type passed in.

For example:

    public Map<String, List<Object>> groupBy(List<Object> objs){
        if(RetType != null) Map<String, List<Object>> ret = (Map<String, List<Object>>)resListType.newInstance();
        if(RetTypeList == null) RetTypeList = SObject.class;
        Map<String, List<Object>> ret = new Map<String, List<Object>>();

        for(Object o: objs){
            String group_name = partitionFn((SObject) o);
            if (ret.get(group_name) == null)
                ret.put(group_name, (List<Object>) resListType.newInstance());
            ret.get(group_name).add(o);
        }
        return ret;
    }

This way, we could cast everything very easily, without depending on special functions.