- リンクを取得
- ×
- メール
- 他のアプリ
- リンクを取得
- ×
- メール
- 他のアプリ
🔹 はじめに
Apex では、Iterable
インターフェースを実装することで、カスタムクラスを for-each
ループで直接使用できる ようになります。
これにより、独自のデータ構造やコレクションを、ネイティブのリスト (List
) やセット (Set
) のように 簡潔に反復処理 できるようになります。
本記事では、Apex における Iterable
の実装方法と、テストクラスを含めた動作確認方法 を紹介します。
🔹 Iterable
インターフェースとは?
Apex の Iterable
は、for-each
ループで反復処理 (iteration
) を可能にする インターフェースです。
Java の Iterable
に似ており、iterator()
メソッドを実装することで、要素を順番に取得できます。
🔹 Iterable
を実装したサンプルコード
以下の MyIterable
クラスでは、List
を Iterable
に変換し、for-each ループで利用できるようにしています。
public class MyIterable implements Iterable<String> { private List<String> strings; // コンストラクタでリストを受け取る public MyIterable(List<String> strings) { this.strings = strings; } // iterator() メソッドを実装(List の iterator を返す) public Iterator<String> iterator() { return strings.iterator(); } }
✅ 実装のポイント
Iterable
インターフェースをimplements
する。- コンストラクタで
List
を受け取る(データをセット)。 iterator()
メソッドでList
のiterator()
を返すことで、for-each ループが使用可能になる。
🔹 for-each
ループでの使用例
この MyIterable
クラスを利用すると、for-each ループで 簡潔に要素を取得 できます。
List<String> strings = new List<String>{'Hello', 'World', 'Salesforce'}; // MyIterable インスタンスを作成 MyIterable iterable = new MyIterable(strings); // for-each ループで要素を取得 for (String str : iterable) { System.debug(str); // "Hello", "World", "Salesforce" が出力される }
通常の List
と同じ感覚で for
ループが使えます! 🚀
🔹 テストクラスの実装
Apex では、テストクラスを作成することで コードの動作を保証 できます。
以下のテストクラスを作成し、Iterable
の動作を検証しましょう。
@IsTest public class MyIterableTest { @IsTest static void testIterableForLoop() { // データを準備 List<String> strings = new List<String>{'Hello', 'World'}; // MyIterable インスタンスを作成 MyIterable iterable = new MyIterable(strings); // for-each ループでデータ取得テスト List<String> result = new List<String>(); for (String str : iterable) { result.add(str); } // 期待されるデータと一致するか確認 System.assertEquals(strings, result); } }
✅ テストのポイント
MyIterable
クラスがfor-each
ループで正しく動作するかを検証。System.assertEquals(strings, result)
を使って 元のデータと一致しているか確認。
このテストを Run Tests
で実行し、成功すれば Iterable
の実装が正しく機能している証拠 です! 🎯
🔹 Iterable
を応用する
✅ カスタムオブジェクトを Iterable
に対応
リストだけでなく、SOQL で取得したレコードのカスタムクラスを Iterable
にすることも可能 です。
例えば、Account
のリストを Iterable
にするクラスを作成すると、以下のようになります。
public class AccountIterable implements Iterable<Account> { private List<Account> accounts; public AccountIterable() { // SOQL でデータ取得 this.accounts = [SELECT Id, Name FROM Account LIMIT 10]; } public Iterator<Account> iterator() { return accounts.iterator(); } }
✅ for-each
ループでレコードを処理
AccountIterable accounts = new AccountIterable(); for (Account acc : accounts) { System.debug('Account Name: ' + acc.Name); }
これにより、SOQL で取得した Account
を直接 for-each
ループで処理 できます!
カスタムオブジェクトを扱う際に、より直感的で可読性の高いコード を書くことができます。
🔹 まとめ
機能 | 実装方法 |
---|---|
Iterable の実装 |
implements Iterable を使用し、iterator() を実装 |
for-each ループで使用 |
for (T item : iterableInstance) {} |
テストクラスの作成 | System.assertEquals(expected, actual) で動作を検証 |
カスタムオブジェクト対応 | SOQL で取得したデータを Iterable に変換 |
Iterable
を活用すると、リストやカスタムオブジェクトをシンプルに処理できるようになる ため、コードの可読性が向上します! 🚀
コメント
コメントを投稿