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
ScriptMonkeyScriptMonkey 

Limitation with addAll and sObject Lists

I found this out the very hard way and I would like to share my findings to either warn others, or find out if I've done something wrong somehow.  Sobjects cannot be handed lists of objects via addAll (even though they can be added objects one at a time through add, and OTHER methods that have sObject lists as parameters can accept object lists).

I'll show by example:
Account a = new Account();
sObject s
LIST<sObject> sOjbList = new LIST<sObject>();
sOjbList.add(s);
sOjbList.add(a);
That works perfectly fine, as you'd expect.
sObject s1;
sObject s2;
LIST<sObject> sList = new LIST<sObject>{s1, s2};
LIST<sObject> sOjbList = new LIST<sObject>();
sOjbList.addAll(sList);
Also works fine.

This, however, will fail.
LIST<Account> aList = new LIST<Account>{new Account(), new Account()};
LIST<sObject> sOjbList = new LIST<sObject>();
sOjbList.addAll(aList);
It gives the errors:
Incompatible argument type LIST for All method on LIST
OR
Incompatible argument type LIST<Account> for All method on LIST<SObject>
(Based on if you're using the Developer Console or something else, like MavensMate)

But don't fret, there's a solution (albeit a silly one)
private LIST<sObject> objToSobj(sObject[] objList)
{
	return objList;
}
That's right, pass your objList through this (and it will let you without problem) and all works fine.

Thoughts?
logontokartiklogontokartik
Very useful findings, thank you for sharing
bob_buzzardbob_buzzard
This is documented behaviour - from the Apex Developer's Guide (bold is mine):

--- snip ---
addAll(List)
Adds all of the elements in the specified list to the list that calls the method. Both lists must be of the same type.
--- snip ---

So they both have to be of the same type, not derived from the same superclass. SObject isn't the same type as account, as while any account can be treated as an sobject, only sobjects that are really instances of an account can be treated as an account.

Rather than executing a method, you can just cast your list to the expected type:

LIST<Account> aList = new LIST<Account>{new Account(), new Account()};
LIST<sObject> sOjbList = new LIST<sObject>();
sOjbList.addAll((List<sobject>)aList);