代入ステートメント
代入ステートメントは、値を変数に代入するステートメントです。
通常、代入ステートメントは次の 2 つの形式のいずれかです。
1[LValue] = [new_value_expression];
2[LValue] = [[inline_soql_query]];上記の形式で、[LValue] は、代入演算子の左側に入力できる式を表します。その具体的な内容は次のとおりです。
- 単純な変数。次に例を示します。
1Integer i = 1; 2Account a = new Account(); 3Account[] accts = [SELECT Id FROM Account]; - 参照解決されたリスト要素。次に例を示します。
1ints[0] = 1; 2accts[0].Name = 'Acme'; - コンテキストユーザーが編集権限を持つ sObject 項目参照。次に例を示します。
1Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco'); 2 3// IDs cannot be set prior to an insert call 4// a.Id = '00300000003T2PGAA0'; 5 6// Instead, insert the record. The system automatically assigns it an ID. 7insert a; 8 9// Fields also must be writable for the context user 10// a.CreatedDate = System.today(); This code is invalid because 11// createdDate is read-only! 12 13// Since the account a has been inserted, it is now possible to 14// create a new contact that is related to it 15Contact c = new Contact(LastName = 'Roth', Account = a); 16 17// Notice that you can write to the account name directly through the contact 18c.Account.Name = 'salesforce.com';
代入は必ず参照によって行われます。次に例を示します。
1Account a = new Account();
2Account b;
3Account[] c = new Account[]{};
4a.Name = 'Acme';
5b = a;
6c.add(a);
7
8// These asserts should now be true. You can reference the data
9// originally allocated to account a through account b and account list c.
10System.assertEquals(b.Name, 'Acme');
11System.assertEquals(c[0].Name, 'Acme');同様に、2 つのリストがメモリ内の同じ値を示すことができます。次に例を示します。
1Account[] a = new Account[]{new Account()};
2Account[] b = a;
3a[0].Name = 'Acme';
4System.assert(b[0].Name == 'Acme');= のほか、有効な割り当て演算子には +=、*=、/=、|=、&=、++、および -- があります。「式の演算子」を参照してください。