Platform Developer I Maintenance - nocovi/sfcerts GitHub Wiki
In this hands-on challenge, you will create a custom Apex class that implements the Iterable. You will then use this class to iterate over a collection of items within a for loop. This exercise will help you understand how to simplify iteration in Apex using the Iterable interface.
Prework:
-
Ensure you have access to a Salesforce Developer Org or a Trailhead Playground.
-
Familiarize yourself with basic Apex programming concepts.
-
Review the Salesforce documentation on the Iterable interfaces.
-
Create a custom Apex class: ** Name: MyIterable
-
- Implements: Iterable
-
- Class variable: private List strings
-
Create a constructor for MyIterable:
-
- Argument: List strings
-
- Initializes the class variable strings from the constructor’s argument strings
-
Implement the iterator method:
-
- Return type: Iterator
-
- Returns an iterator for the strings list strings.iterator();
-
Create a test class:
-
- Name: MyIterableTest
-
- Annotation: @IsTest
-
Add a test method to the test class:
-
- Name: testIterableForLoop
-
- Type: void()
-
- Annotation: @IsTest
-
Steps:
-
- Create a list of strings: List strings
-
- Values: ‘Hello’,’World’
-
- Create an instance of MyIterable with the list of strings.
-
- Use a for loop to iterate over the MyIterable instance.
-
- Print each string using System.debug.
-
Run the test class:
-
Open the Developer Console
-
- Navigate to the Test menu
-
- Select New Run
-
- Select the MyIterableTest class and run the test
-
Verify the Output ** Check the debug logs to verify that the for loop iterated over the collection and printed each string.
-
- Expected Output:
-
- The debug logs should display the following output:
-
-
- DEBUG | Hello
-
-
-
- DEBUG | World
-