2

How is the Start method from Batchable Interface able to return two different return types? Iterable or QueryLocator.

As far as Function Overloading is concerned, methods can be overloaded based on different input parameters. But its not possible to overload a method based on different Return Types.

What programming feature is used in Batchable Interface? enter image description here

I tried to create a similar Interface, but its not allowing me to save it. enter image description here

1
  • I shared an example "generic batchable" that does this (see this); it might handy to know.
    – sfdcfox
    Aug 18 '21 at 14:50
5

Simple; the Database.QueryLocator implements the Iterable interface, so actually you are always returning an Iterable of some form.

You can consider the ability to define your start method as returning Database.QueryLocator as using the covariant return type functionality of other object oriented languages. That the Salesforce documentation specifically shows two different signatures is just to help you understand that both options are available. Covariant return types are not supported across the Apex language, but rather in special cases like this.

It is worth noting that Apex is not a formally defined language and has some weirdnesses.

For example, it doesn't really support generics (templating) either. What you see is somewhat "smoke and mirrors". To illustrate this, you can define a batch class as implementing Database.Batchable<SObject> yet the execute method (when processing Account records, for example) can receive List<Account> and there will be no compilation or runtime error (as long as the start method selects Account records).

2
  • Okay, thanks for answering. Does that mean Batchable Interface has only one method declaration for Start method? Which should be of signature "System.Iterable start(Database.BatchableContext jobId)", and other signature is only added for our understanding?
    – Ram
    Aug 18 '21 at 15:20
  • Answer updated to mention covariant return types.
    – Phil W
    Aug 18 '21 at 16:21

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.