function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Abhik SahaAbhik Saha 

Batchable<SObject> Interface: Isn't it an unusual interface?

If you look at the general approach to write a batch, it asks to implement the Batchable interface. The sample code is like this -
global class Accountupdate implements Database.Batchable<sObject> 
{ 
:
:
Here, one thing is absurd - what is the use of datatype sObject in the interface name? Can we write an interface like this?
Also, Salesforce doc says you need to implement start method -
global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}
But in an interface how can you define a method with 2 return types? Again, when you actually implement this, you are implementing with just any one of these return types - Database.QueryLocator or Iterable<sObject>. How does this work?

In a nutshell, how has salesforce written the Batchable interface?
 
anka lexanka lex
Hi Abhik,

Salesforce tells to use any one of them not both return types in for start() method.  The below will work.

global Database.QueryLocator start(Database.BatchableContext bc) {
}

Please check below links which will help you.
https://developer.salesforce.com/forums/?id=906F00000008m2xIAA
https://webkul.com/blog/batch-apex/

Thanks,
Shubham saini 14Shubham saini 14

Hello,

global class LeadProcessor implements Database.Batchable<sObject>

It's a syntax of batch apex

global class LeadProcessor implements Database.Batchable<sObject> {

    global Integer recordsProcessed = 0;
   
   // return type should be Database.QueryLocator or Iterable<sObject>, not both

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(
            'SELECT ID FROM Lead'
        );
    }

    global void execute(Database.BatchableContext bc, List<Lead> scope){
        // process each batch of records
        List<Lead> Leads = new List<Lead>();
        for (Lead lead : scope) {
            lead.LeadSource = 'Dreamforce';
            Leads.add(lead);
            recordsProcessed++;
        }
        update Leads;
    }    

    global void finish(Database.BatchableContext bc){
        System.debug(recordsProcessed + ' records processed. Shazam!');
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, 
            JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id = :bc.getJobId()];
        System.debug('job  '+job);
    }  
}