4

This question already has an answer here:

I understand I can declare a variable with the final keyword as below...

private final List<User> userList = [SELECT Id FROM User];

... That will generate an array that, when supplied with a value, can't be changed. I'd like to do the same thing, only using a Map.

I've tried:

private final Map<Id, User> userList = [SELECT Id FROM User];

But I can an error arround trying to supply a List<> type to a Map<>, which I understand. Additionally I've tried:

private final Map<Id, User> mapUserIdToUser {
  get {
    if (mapUserIdToUser == null) {
      mapUserIdToUser = new Map<Id, User>();
      for (User user : [SELECT Id FROM User]) {
        mapUserIdToUser.put(user.Id, user);
      }
    }

    return mapUserIdToUser;
  }
}

But then I get the following error:

Methods are final by default, Use virtual to declare methods that can be overriden

Ideally I'd like to do something as short and sweet as the first line of code I supplied at the top, so really I'm looking at the cleanest way possible to declare a Map<Id, SObject> using the final keyword as once this variable has been supplied with values, it won't change.

Edit

I may be misunderstanding something pretty simple, but given the error I know I could just remove final and write something like below:

private final Map<Id, User> mapUserIdToUser {
  get {
    if (mapUserIdToUser == null) {
    [...]

But would this act as final and disallow any changes to the variable?

marked as duplicate by Adrian Larson apex May 31 '17 at 18:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4

Try this:

private final Map<Id, User> userList = new Map<Id, User>([SELECT Id FROM User]);
  • Perfect, I figured it'd be something simple. I think I was overthinking it! – Dan Jones May 31 '17 at 12:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.