3

Considering the code snippet:

..
List<SObject> lstSObject = sentence == true ? List<typeA__c>() : List<typeB__c>(); 

Salesforce doesn't explain much as this operator should be straightforward.

And following the principle of the java operator too. https://en.wikipedia.org/wiki/%3F:#Java

To confirm my thought, is the compiler verifying what is bidding on the interface (List) and considering its type itself?

1 Answer 1

8

That's not true, for the same SObject types, it works, you just forgot new:

List<SObject> lstSObject = (sentence ? new List<typeA__c>() : new List<typeA__c>());

And for different SObject types it works too, but you should do casting:

List<SObject> lstSObject = (sentence ? (List<SObject>) new List<typeA__c>() : (List<SObject>) new List<typeB__c>());
2
  • You're right @Mariia I've mistyped during the edition and hasn't added the cast internally from List<Object> thanks!
    – Carlos
    Feb 22, 2022 at 17:41
  • 1
    And the reason why the cast is necessary is because ternaries require that both possible results return the same type.
    – Derek F
    Feb 22, 2022 at 18:22

You must log in to answer this question.

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