Apex-変数

JavaとApexは多くの点で似ています。JavaとApexでの変数宣言もまったく同じです。ローカル変数を宣言する方法を理解するために、いくつかの例について説明します。

String productName = 'HCL';
Integer i = 0;
Set<string> setOfProducts = new Set<string>();
Map<id, string> mapOfProductIdToName = new Map<id, string>();

すべての変数に値nullが割り当てられていることに注意してください。

Declaring Variables

文字列や整数などの変数をApexで次のように宣言できます-

String strName = 'My String';  //String variable declaration
Integer myInteger = 1;         //Integer variable declaration
Boolean mtBoolean = true;      //Boolean variable declaration

Apex variables are Case-Insensitive

これは、変数 'm'が2回宣言されており、両方が同じものとして扱われるため、以下のコードはエラーをスローすることを意味します。

Integer m = 100;
for (Integer i = 0; i<10; i++) {
   integer m = 1; //This statement will throw an error as m is being declared
   again
   System.debug('This code will throw error');
}

Scope of Variables

Apex変数は、コードで宣言された時点から有効です。したがって、同じ変数をコードブロックで再定義することはできません。また、メソッドで変数を宣言すると、その変数のスコープはその特定のメソッドのみに制限されます。ただし、クラス変数にはクラス全体でアクセスできます。

Example

//Declare variable Products
List<string> Products = new List<strings>();
Products.add('HCL');

//You cannot declare this variable in this code clock or sub code block again
//If you do so then it will throw the error as the previous variable in scope
//Below statement will throw error if declared in same code block
List<string> Products = new List<strings>();