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?.profiles
to a variable and perform anis
check to eliminate the possibility of havingnil
values. This helps narrow-down the variable type toProfile[]
.And if you choose to return or continue within the
if
block, theelse
block is not required, as the type will be narrowed after theif
block anyway.