I have a List<sObject> scope and I want to cast it to a concrete type: List<My_Concrete_Type__c>

I tried scope.getSobjects('My_Concrete_Type__c') but this doesn't compile. How can I get a List<My_Concrete_Type__c>?


Have you tried doing this?

List<My_Concrete_Type__c> concreteTypeList = (List<My_Concrete_Type__c>) scope;

You can return an iterator of a specific type from your start method and avoid the need to cast entirely.

public class MyBatch implements Database.Batchable<MyObject__c>
    public List<MyObject__c> start(Database.BatchableContext context)
        return [/*query*/];
    public void execute(Database.BatchableContext context, List<MyObject__c> concreteScope)
        // execute logic
    public void finish(Database.BatchableContext context)
        // finish logic
  • Definitely the preferred method when possible. – sfdcfox Oct 18 '16 at 23:50
  • @sfdcfox Do you know if it costs you any governors? You can return 50M when using a QueryLocator, but I'm not sure if that holds or not with this strategy. I haven't found time to experiment myself. – Adrian Larson Oct 18 '16 at 23:53
  • Actually, you'll want to use implements Database.Batchable<SObject> and start( ... List<MyObject__c> scope), along with the Database.QueryLocator return type. The compiler doesn't actually verify the scope parameter has the same sobject type as the interface sobject type. – sfdcfox Oct 19 '16 at 0:02
  • Hmm. I thought it didn't allow me to do that the first time I tried and haven't checked since. I'll have to experiment after all. – Adrian Larson Oct 19 '16 at 0:06

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.