As most stories here begin, I was writing some code for a project that I was working on, and stumbled across an oddity when writing some unit tests. I was testing a method that has a Set<sObject>
parameter, and I was attempting to pass this method a Set<Account>
.
As Account
inherits from sObject
, I thought this would work fine. However, when running my test, I got the error
Method does not exist or incorrect signature: [TestClass].someMethod(
Set<Account>
)
Yes, the method that I was testing expects an argument of Set<sObject>
, but an Account
can be up-cast to an sObject
, and Salesforce handles that implicitly, right?
Since Salesforce was throwing a fit when I tried to rely on implicit casting, the next thing I tried was explicitly up-casting. When I tried to explicitly up-cast my set, I was greeted with a different error
Line:
someNumber
, Column:otherNumber
Incompatible types since an instance ofSet<Account>
is never an instance ofSet<SObject>
This can be reproduced with the following snippet
Set<sObject> testSet1;
Set<Account> testSet2 = new Set<Account>();
testSet1 = (Set<sObject>)testSet2;
I haven't found anything in the documentation to suggest that up-casts for sets aren't allowed. Given that we can up-cast Lists and Maps, I feel this is rather unexpected.
Furthermore, knowing that an Apex set is really a Java HashSet
in the back-end (look at the bottom of this page of documentation), I tried to look for documentation to see if this is somehow dictated by Java, but I came up empty there as well.
I've been able to move on with my project, but this leaves me wondering...
Is there some documentation (Salesforce or Java) that explains this behavior? Failing that, can someone cobble together a feasible explanation for why Sets can't be up-cast?
Set<SObject>
in general.List<sObject>
set<ID>
around. :-)