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。

宣告變數

可以在 Apex 中宣告變數,如下所示:String 和 Integer

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

Apex 變數不區分大小寫

這意味著下面給出的程式碼將丟擲一個錯誤,因為變數“m”已被宣告兩次,並且兩者將被視為相同。

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');
}

變數作用域

Apex 變數從其在程式碼中宣告的點開始有效。因此,不允許在程式碼塊中重新定義相同的變數。此外,如果在某個方法中宣告任何變數,那麼該變數的作用域僅限於該特定方法。然而,類變數可以在整個類中訪問。

示例

//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>();
廣告