0

I'm doing a challenge for a course and I was trying in a class, not in execute anonymous, and in the class, it show errors and the execute anonymous don't. Why that?

Look the photos to understand, is the same code. enter image description here

enter image description here

1 Answer 1

3

Executable statements like:

category.put('Apex',postApex);

Are not allowed outside of methods inside a class. In Execute Anonymous, however, your code is implicitly wrapped in a function.

Either you can use a constructor for instance methods, or static variables with a static initializer block.

public class Challenge1 {
  Map<String, List<String>> category = new Map<String, List<String>>();
  List<String> postApex = new List<String>('...','...');
  List<String> postLightning = new List<String>('...','...');
  // Constructor has no return type and name same as class
  public Challenge1() {
    category.put('Apex',postApex);
    category.put('Lightning',postLightning);
  }
}

public class Challenge1 {
  static Map<String, List<String>> category = new Map<String, List<String>>();
  static List<String> postApex = new List<String>('...','...');
  static List<String> postLightning = new List<String>('...','...');
  // static initialization for static variables
  static {
    category.put('Apex',postApex);
    category.put('Lightning',postLightning);
  }
}

Execute Anonymous is a weird type of hybrid Apex that has different rules than either triggers or normal, compiled classes. This is so that such code is easier to execute, since you don't need to write a class to contain data and methods.

You must log in to answer this question.

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