2

I am new to Salesforce and have what I though would be very simple code. For some reason this is throwing an error:

public class GetSet {
    public class BasicProperty {
        public integer prop {
            get { return prop; }
            set { prop = value; }
        }
    }

    BasicProperty bp = new BasicProperty();
    bp.prop = 5;}

I have programmed in Java before and am aware of accessing properties, but this is the literal example from the Summer '14 Documentation. I get the following error:

Error: Compile Error: unexpected token: '=' at line 13 column 12

I cannot see any reason for this not to compile. Any ideas?

EDIT:

Say you have a class such as:

public class printer {
   String message;
}

When you do a debug execute the following code runs fine.

Printer printer = new Printer();
printer.message = "Hello World";

But when I write the same thing in a new class, it fails. Salesforce is a very frustrating platform.

2 Answers 2

4

Try assigning the Property values in Constructor or Method

public class GetSet {
   public class BasicProperty {
        public integer prop {
             get { return prop; }
             set { prop = value; }
        }
   }
  //You can assign values in Constructor like
  puclic GetSet()
  {
     BasicProperty bp = new BasicProperty();
     bp.prop = 5;
  }
  //Or create a method
  public void getData()
  {
     BasicProperty bp = new BasicProperty();
     bp.prop = 5;
  }
}
1
  • If I have a class that has get and set methods, it runs fine in the Execute Anonymous Window. When I write the same code in another class, it does not run. Say class.setName('Name'); runs fine in the Execute Anonymous Window. It does not run when I write the same thing in another class. Any idea why that happens?
    – Geoff
    Aug 3, 2014 at 17:55
0

In Apex (and Java) class instance properties and fields can only be assigned to within the scope of a constructor or a method.

The Execute Anonymous window is an exception to this rule which allows you to execute arbitrary statements as if you were already within the scope of a method.

The way I like to think of the Execute Anonymous window is that you enter code in there, and then, when you run it the platform wraps it in a 'main' method for you and executes it. This allows you to execute statements like the one in your example which would normally need to be within the scope of method.

There is more information in the Anonymous Blocks documentation.

1
  • Yeah, I did not realize it was with the scope of an init(), main() or similar. Salesforce is not terribly well documented and this was driving me crazy.
    – Geoff
    Aug 5, 2014 at 23:31

You must log in to answer this question.

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