0

Is it possible to pass a concrete list of objects into a method that expects a list of sObjects?

E.g.

list<account> accs = [select id, name from account];
PassToMethod(accs);
...

public void PassToMethod(list<sObject> objects){ ... }

In my particular case I want a generic method that accepts Database.UpsertResult[] + list of sObjects that were upserted. The method will then capture information (id, name) regarding any upserts that failed.

Derek F
  • 61,401
  • 15
  • 50
  • 97
AndeeWork
  • 3
  • 1
  • 3

2 Answers2

0

Yes, this is perfectly legal in Apex.

sfdcfox
  • 489,769
  • 21
  • 458
  • 806
0

For things like this, it's usually faster to just give it a try yourself.

Yes it is possible, because:

  • You're using a List
  • Account inherits from SObject
  • You're effectively up-casting (going from a concrete type to a more generic type)

It'd also be possible with a Map<Id, Account> (if your method took a Map<Id, SObject>), as long as the type of the map's key is the same and the value types are compatible. It's not possible with a Set<Account> (if your method took a Set<SObject>) though.

There are also some circumstances where you can down-cast (from a generic type to a concrete type), though there are additional restrictions on when down-casting is possible.

Derek F
  • 61,401
  • 15
  • 50
  • 97