I recently came across a rather interesting syntax of a map in a batch apex which I would be grateful if anyone can explain to me how it's actually working:

global class CommissionSharingRecalc implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT Id, Commission_Approver__c, Payee__c 
                                     FROM Commission__c]);  

    // The executeBatch method is called for each chunk of records returned from start.  
    global void execute(Database.BatchableContext BC, List<sObject> scope){
       // Create a map for the chunk of records passed into method.
        Map<ID, Commission__c> commissionMap = new Map<ID, Commission__c>((List<Commission__c>)scope); 

My curiosity is on this part of the code:

Map<ID, Commission__c> commissionMap = new Map<ID, Commission__c>((List<Commission__c>)scope); 

How is the id key and Commision__c values being passed into the Map without the map add method. Thanks for the responses.


The Apex map class includes this convenience constructor:

public Map<ID,sObject>(List<sObject> recordList)

because it is common to want to build a map where the key is the ID and the value is the SObject. (To build that map yourself, you would have to loop over all the SObject in the list and put each one into the map.)

You see this used a lot in triggers where code needs to lookup an SObject by its ID e.g.:

Map<Id, Contact> m = new Map<Id, Contact>([select Id, Name from Contact]);

Your case is a little extra confusing because there is a cast (List<Commission__c>) also included.

  • 1
    The cast is necessary because they are using a generic SObject array. – sfdcfox Dec 12 '14 at 19:41
  • I had looked at the map class documentation but didn't look hard enough at its various constructors - thanks Keith C for pointing it out. – sw6 - KTBFFH Dec 12 '14 at 19:46

I am looking to do something similar - assign values to a map from the QueryLocator method to a map, but I would like to assign negative values to one map, and positive values to another, but can't think how to do this in scope! Any suggestions would be a great help! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.