In my Ballerina program I have the below nested record structure and, I want to iterate through the profiles array within associatedProfiles of an Allotment record.
Here's a simplified version of my code:
type Allotment record {
string inventoryBlockName?;
AssociatedProfiles associatedProfiles?;
};
type AssociatedProfiles record {
Profile[] profiles?;
};
type Profile record {
string creatorCode?;
};
I tried using a foreach loop as shown below, but the compiler is raising issues.
foreach Profile profile in allotment.associatedProfiles?.profiles? {
// Code logic here
}
So what is the recommended approach to iterate over optional nested records in Ballerina?
In this scenario, it is recommended to assign the
allotment.associatedProfiles?.profilesto a variable and perform anischeck to eliminate the possibility of havingnilvalues. This helps narrow-down the variable type toProfile[].And if you choose to return or continue within the
ifblock, theelseblock is not required, as the type will be narrowed after theifblock anyway.