ループへのNull-Handlingの埋込み
ループがNULL値でどのように動作するかを理解することで、コードの追加行数を回避できます。
変数recentOrders
がList
の場合、次のループはリスト内の各要素を処理するか、変数がnull
またはリストが空の場合にスキップします:
// Process recent customer orders (if any, otherwise skip)
for (order in recentOrders) {
// Do something here with current order
}
変数
recentTransactions
がMap
の場合、次の条件付きブロックは、recentTransactions
がnull
ではなく、マップ・エントリが少なくとも1つ含まれている場合にのみ実行されます:// Process supplier's recent transaction (if any, otherwise skip)
for (transaction in recentTransactions) {
// Do something here with each transaction referencing each map
// entry's key & value using transaction.key & transaction.value
}
String
変数には、null
、空の文字列(""
)または少なくとも1つの文字を含めることができます。 変数middleName
がString
の場合、次の条件付きブロックは、middleName
がnull
ではなく、少なくとも1文字を含む場合にのみ実行されます:
// Process the characters in the customer's middle name
for (c in middleName) {
// Do something here with each character 'c'
}
for
ループで、null
の可能性がある変数に対してメソッドを直接呼び出す場合は、safe-navigation演算子(?.
)を使用して、変数がnull
の場合にエラーを回避します:
// Split the recipientList string on commas, then trim
// each email to remove any possible whitespace
for (email in recipientList?.split(',')) {
def trimmedEmail = email.trim()
// Do something here with the trimmed email
}