0

I'm trying to find the most simple way to cast a map<Object, List<Sobject>> in any other type like, String, Integer and etc..

Anyone knows how to do this?

This is my code

Map<Object, SolicitationItem__c[]> mapHierarchyRequestToItem = (Map<Id,SolicitationItem__c[]>) Collection.of(newRecordsMap.values()).group().byField(SolicitationItem__c.HierarchySolicitation__c).get();

ERROR:

Incompatible types since an instance of Map<Object,List> is never an instance of Map<Id,List<SolicitationItem__c>> (11:72)

2
  • What is Collection.of()? Are you using some library? Please edit to add details.
    – David Reed
    Apr 25, 2022 at 18:33
  • Yes, i'm using this collection => github.com/wozniak-michal/apex-collection-library, and i'm trying to know how is the simplest way to convert a Object set in any other type i want.... I'd like to convert my map<Object... in any other type like string, integer Apr 25, 2022 at 18:37

1 Answer 1

5

Simplifying things greatly, sets (and the keysets of maps) do not contain enough type information for you to cast between different types. I had a question that went over this in greater detail (Is there a specific reason why we can't upcast sets?)

Lists can be cast, and Maps can be cast as long as the key type isn't changing. Sets can never be cast (at time of writing).

If your mapHierarchyRequestToItem map contains Ids as the key, you'll need to extract them one by one inside of a loop.

e.g.

Set<Id> extractedIds = new Set<Id>();
for(Object data :myMap.keySet()){
    // You can't cast the set, so you need to cast the individual items in the set
    extractedIds.add((Id)data);
}
3
  • 4
    And yes, it'd probably be a good idea to check to see if something looks like an Id before casting it as an Id. instanceof is not really a good check for that though. Instanceof Id only checks that the fifth character is 0, which enables hilarity like system.debug('πŸ™‚πŸ™‚0πŸ™‚πŸ™‚πŸ™‚πŸ™‚πŸ™‚' instanceof Id ? 'Looks like an Id to me!' : 'Not an Id');. Yes, that's a 0 in the fifth position (and smiley emoji, 2-byte characters, filling up the rest), and yes instanceof thinks it's an Id.
    – Derek F
    Apr 25, 2022 at 18:55
  • Thanks Derek, i'd want to sure what's in my mind, but it is terrible lol Apr 25, 2022 at 19:01
  • @DerekF It's a little more capable than "just checks fifth char...", but hilariously less capable than I'd realized. I would have assumed it at least checked [a-zA-Z0-9]{15} or something like that.
    – sfdcfox
    Apr 25, 2022 at 19:37

You must log in to answer this question.

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