I get the error First error: Invalid conversion from runtime type CustomIterable to System.Iterable when trying to use a customer iterable in a batch job.

My custom iterable class:

global class CustomIterable implements Iterator<SObject>{ 

List<SObject> sobjs {get; set;} 
Integer i {get; set;} 
public CustomIterable(){ 
   sobjs = new List<SObject>();

   List<Account> accs = [SELECT Id, Name, OFAC_Last_Check_Date__c,OFAC_Passed__c FROM Account]; 
   for( Account acc : accs ) {

   List<Contact> cons = [SELECT Id, FirstName, LastName, OFAC_Last_Check_Date__c,OFAC_Passed__c FROM Contact]; 
   for( Contact con : cons ) {
   i = 0; 
global boolean hasNext(){ 
   if(i >= sobjs.size()) 
       return false; 
       return true; 
global SObject next(){ 
   if(i == 8){ i++; return null;} 
   return sobjs[i-1]; 

This is how I call the above code:

global Iterable<SObject> start(Database.batchableContext info){ 
    //Iterable<SObject> myIter = (Iterable<SObject>)new CustomIterable();
    return new CustomIterable(); 

I followed this example from the documentation. I am trying use two objects in the batch job, hence the custom iterable.


  • I don't have anything to add to Adrian's response.... but I am a busybody and will comment anyway. Why did you choose to implement a custom iterator instead of including the contacts as a subquery within the initial account query? Pure curiosity, I admit. – Sebastian Kessel May 26 '16 at 22:04
  • The client is using a customized NPSP and is treating contacts and accounts as two separate, independent objects. – jscho May 31 '16 at 14:50

Take a look at Custom Iterators, you are mixing up Iterable and Iterator (crazy, I know). You need to return an Iterable where you are using an Iterator (you only implement the latter). Fortunately, you can just implement both.

class CustomIteratable implements Iterable<SObject>, Iterator<SObject>
    public Iterator<SObject> iterator() { return this; }
    public Boolean hasNext() { /*implementation*/ }
    public SObject next() { /*implementation*/ }
| improve this answer | |

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.