機械翻訳について

ループへのNull-Handlingの埋込み

ループがNULL値でどのように動作するかを理解することで、コードの追加行数を回避できます。

変数recentOrdersListの場合、次のループはリスト内の各要素を処理するか、変数がnullまたはリストが空の場合にスキップします:

// Process recent customer orders (if any, otherwise skip)
for (order in recentOrders) {
  // Do something here with current order
}
変数recentTransactionsMapの場合、次の条件付きブロックは、recentTransactionsnullではなく、マップ・エントリが少なくとも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つの文字を含めることができます。 変数middleNameStringの場合、次の条件付きブロックは、middleNamenullではなく、少なくとも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
}