如何在 Ballerina 中迭代嵌套和可选记录数组?

问题描述 投票:0回答:1

在我的 Ballerina 程序中,我有以下嵌套记录结构,并且我想迭代

profiles
记录的
associatedProfiles
内的
Allotment
数组。

这是我的代码的简化版本:

type Allotment record {
    string inventoryBlockName?;
    AssociatedProfiles associatedProfiles?;
};

type AssociatedProfiles record {
    Profile[] profiles?;
};

type Profile record {
    string creatorCode?;
};

我尝试使用

foreach
循环,如下所示,但编译器出现问题。那么,在 Ballerina 中迭代可选嵌套记录的正确方法是什么?

foreach Profile profile in allotment.associatedProfiles?.profiles? {
    // Code logic here
}
foreach record ballerina ballerina-swan-lake
1个回答
0
投票

在这种情况下,建议将

allotment.associatedProfiles?.profiles
分配给变量并执行
is
检查以消除具有
nil
值的可能性。这有助于将变量类型缩小到
Profile[]

Profile[]? profiles = allotment?.associatedProfiles?.profiles;

if profiles is () {
    // Handle `profiles` being `()` due to `AssociatedProfiles` or `Profile` being `()`
} else {
    // `profiles` is `Profile[]`
    foreach Profile profile in profiles {
        io:println(profile.creatorCode);
    }
}

如果您选择在

if
块内返回或继续,则不需要
else
块,因为无论如何,在
if
块之后类型都会缩小。

Profile[]? profiles = allotment?.associatedProfiles?.profiles;

if profiles is () {
    // Handle `profiles` being `()` and return.
    return;
}

// `profiles` is `Profile[]` here.
foreach Profile profile in profiles {
    io:println(profile.creatorCode);
}
© www.soinside.com 2019 - 2024. All rights reserved.