0

Trying to create a method to return a Map of SObjects using any field I want (not Id or I would use the Map constructor that takes a List).

private static Map<String, SObject> getSObjectMap(List<SObject> records, String fieldName) {
  String sObjectTypeString = String.valueOf(records[0].getSObjectType());
  Type t = Type.forName('Map<String,' + sObjectTypeString + '>');
  Map<String, SObject> mapRecords = (Map<String, SObject>) t.newInstance();
  for (SObject record: records) {
    String key = (String) record.get(fieldName);
    mapRecords.put(key, record);
  }
  return mapRecords;
}

REVISED (per Derek F) Map variable name from "map" to "mapRecords" to resolve "Unexpected token: Map" and "Expecting ';' but was ','" and "Unexpected token: map" for the second line.

1
  • I was typing up an answer for your edit (which I thought should be a separate question). If you feel like making another question for it, I pretty much have an answer waiting for you.
    – Derek F
    Oct 5, 2020 at 14:45

1 Answer 1

6

map is a keyword, and it cannot be used as an identifier (the name of a variable, method, etc...).

Chose a different name for your variable, update the lines of code which use that variable, and you should be fine.

+edit:

To be a bit more specific, you can't use a reserved word (loop, and, map, etc...) as an identifier by itself, but it can be part of an identifier. myMap, ripAndTear, etc... There just needs to be something to prevent the compiler (parser?) from thinking it's something it isn't.

4
  • Thanks... Wish I got a message like "Reserved name: map". The error messages were taking me in the wrong direction. Oct 5, 2020 at 13:48
  • @nstuyvesant Making a compiler that gives useful error messages is hard, so I don't really fault Salesforce too much for that. There is a doccumentation page for reserved words. Another thing to keep in mind is that Apex is pretty case-insensitive. 'Map' == 'map' == 'MAP' (anything that involves hashes though, like data put into a Set or the key of a Map is very much case-sensitive).
    – Derek F
    Oct 5, 2020 at 13:54
  • Thanks @Derek F. Knowing Apex is not case-sensitive is helpful as I've seen references to SObject and sObject in Salesforce's code examples that had me scratching my head. Oct 5, 2020 at 14:02
  • While this is syntactically correct, I guess my approach is problematic. Oct 5, 2020 at 16:24

You must log in to answer this question.

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