Why getting an Invalid initializer error?

293    Asked by AnishaDalal in Salesforce , Asked on Apr 16, 2021

In my custom object, I have two fields Name__c and QuestionString__c

I am trying to initialize a map with Name__c as key and QuestionString__c as a value from a SOQL.

Map ppmap = new Map([SELECT Name__c, QuestionString__c FROM PObj__c]);

I tried the above but I get the error as

Invalid initializer type List found for Map: expected a Map with the same key and value types, or a valid SObject List

Can someone tell me if it is possible to initialize a map directly (without "Id") from SOQL?

Answered by anu rhea

Getting this error means, you can only use an initializer for a Map. If you want to map one field to another, you need a loop.

Valid:

  Map data = new Map([ SELECT ... FROM ... WHERE ... ]);

Not Valid:

  Map data = new Map([ SELECT ... FROM ... WHERE ... ]);

Looping:

  Map data = new Map(); for (MyObject__c record : [SELECT ... FROM ... WHERE ...]) { data.put(record.Field1__c, record.Field2__c); }


Your Answer

Interviews

Parent Categories