function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
King KooKing Koo 

"Variable does not exist' compile time error

Hi there

 

I always have the habit of declaring my variables first before I use them.  Say,

public class a
{
  public integer v1 = 3;
  public integer v2 = 5 * v1;
}

 

 

So I never have encountered this error before:   it looks like if you declare integer v2 first before you declare integer v1, Apex actually gives you an error.  For example,

 

public class a
{
  public integer v2 = 5 * v1;
  public integer v1 = 3;
}

 

I thought, that makes sense, because Apex only scans the code once, top-down, so when it scans the first line, it was not able to resolve the value of v1, so it spits out the "Variable does not exist" error.

 

HOWEVER, now, if I change v2 from simply a variable to a property, i.e.

public class a
{
  public integer v2
  { 
    get {return 5 * v1;}
    set;
  }
  public integer v1 = 3;
}

 

This time the compiler doesn't complain!

 

I'm trying to understand this and thought, maybe because when I have a code like that, Apex is not trying to calculate the value of v2 at runtime - it'll only calculate the value of v2 when it is actually being accessed.

 

The part where I'm not connecting the dots is, still then, why is it not complaining about v1 in that case?

 

Any ideas?

 

Thanks

King

Vinita_SFDCVinita_SFDC

I understand Variables are executed before methods.

rajjjjrajjjj
Variable declarations get executed first before Getters and Setters. Thats the reason why u wouldn't see any errors.