You need to sign in to do that
Don't have an account?
Chad.Pfrommer
Casting to Lists to List<ancestor> works fine, but casting Sets to Set<ancestor> does not
The following code works fine:
The following code, however, does not compile:
It results in a "Incompatible types since an instance of Set<Datetime> is never an instance of Set<Object>" compilation error.
Same thing here:
List<Datetime> dtList = new List<Datetime>();
List<Object> oList = (List<Object>) dtList;
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;
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:
}
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
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?List<SObject> soList = (List<SObject>) aList; // <--- works fine
Set<Account> aSet = new Set<Account>();
Set<SObject> soSet = (Set<SObject>) aSet; // <--- compilation error
It's interesting that apex has the runtime exception when doing this with Lists:
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.