2

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 ) {
       sobjs.add(acc);
   }

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

Thanks!

2
  • 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. Commented May 26, 2016 at 22:04
  • The client is using a customized NPSP and is treating contacts and accounts as two separate, independent objects.
    – jscho
    Commented May 31, 2016 at 14:50

1 Answer 1

2

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*/ }
}

You must log in to answer this question.

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