Are you facing Unexpected Token ERROR?

3.6K    Asked by AnushaAcharya in Salesforce , Asked on Apr 22, 2021

enter image description here

Answered by Ankit Chauhan

Please copy and paste your code into your question and use the {} tool or Ctrl-K to format it appropriately as code if you are facing an unexpected token. Screenshots are generally harder to work with. In this case, you have two simple syntax errors:

public Map oppMapMethod {
This method declaration is missing its parameter list, which in this case is empty. You must include an empty parameter list () in any method declaration that doesn't take parameters, the only exception being a getter/setter on a property. Hence:
public Map oppMapMethod() {
The other issue is that your object creation syntax is wrong.
Map oppMap = new Map

Object constructors are method calls, and also require parentheses as such. Additionally, all statements in Apex end with a semicolon, as in most C/Java family languages.

Map oppMap = new Map();
However, You don't have to do most of this code anyway, because Apex has a "magic" syntax for initializing sObject maps of Id to sObject. Just pass the SOQL-query list directly to the Map constructor:
Map oppMap = new Map([SELECT Id, .... FROM Opportunity ...]);
Then you don't need a separate list or for loop at all, and your method becomes a one-liner:
return new Map([SELECT Id, .... FROM Opportunity ...]);

Hope this helps you!



Your Answer

Interviews

Parent Categories