3

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>?

2 Answers 2

4

Have you tried doing this?

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

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
    }
}
4
  • Definitely the preferred method when possible.
    – sfdcfox
    Commented Oct 18, 2016 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
    Commented Oct 18, 2016 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
    Commented Oct 19, 2016 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
    Commented Oct 19, 2016 at 0:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .