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
Chad.PfrommerChad.Pfrommer 

Casting to Lists to List<ancestor> works fine, but casting Sets to Set<ancestor> does not

The following code works fine:
List<Datetime> dtList = new List<Datetime>();
List<Object> oList = (List<Object>) dtList;

The following code, however, does not compile:
Set<Datetime> dtSet = new Set<Datetime>();
Set<Object> oSet = (Set<Object>) dtSet;

It results in a "Incompatible types since an instance of Set<Datetime> is never an instance of Set<Object>" compilation error.

Same thing here:
 
public class TestA {
}
public class TestB extends TestA {
}

List<TestB> tbList = new List<TestB>();
List<TestA> taList = (List<TestA>) tbList; // <--- compiles fine

Set<TestB> tbSet = new Set<TestB>();
Set<TestA> taSet = (Set<TestA>) tbSet;  // <--- doesn't compile
 
And here:
 
List<Account> aList = new List<Account>();
List<SObject> soList = (List<SObject>) aList; // <--- works fine

Set<Account> aSet = new Set<Account>();
Set<SObject> soSet = (Set<SObject>) aSet; // <--- compilation error
 
Am I missing something obvious?  If not, is there a reason you can't cast Sets like this?
thienthangthienthang
Maybe you could find out the reason here (http://stackoverflow.com/questions/6319163/cant-cast-generic-sets). Hope this help.
 
Chad.PfrommerChad.Pfrommer
Interesting, and I understand the potential problems with casting Collections of objects to Collections of parent objects.  I'm assuming at some point someone said, "debugging runtime exceptions arising from this problem could be very difficult, so let's just head it off at the pass and throw a compile time error".

It's interesting that apex has the runtime exception when doing this with Lists:
List<Datetime> dtList = new List<Datetime>();
List<Object> oList = (List<Object>) dtList;
oList.add(5); // <--- generates runtime exception "System.TypeException: Collection store exception adding Integer to List"

But a compile time exception when trying to do that type of cast with Sets.