Embracing Null-Handling in Loops

You can avoid many extra lines of code by understanding how loops behave with null values.

If a variable recentOrders is a List, then the following loop processes each element in the list or gets skipped if the variable is null or the list is empty:

// Process recent customer orders (if any, otherwise skip)
for (order in recentOrders) {
  // Do something here with current order
}
If a variable recentTransactions is a Map, then the following conditional block executes only if recentTransactions is not null and contains at least one map entry:
// 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
}

A String variable can be null, an empty string (""), or can contain at least one character in it. If a variable middleName is a String, then the following conditional block will execute only if middleName is not null and contains at least one character:

// Process the characters in the customer's middle name
for (c in middleName) {
  // Do something here with each character 'c'
}

If your for loop invokes a method directly on a variable that might be null, then use the safe-navigation operator (?.) to avoid an error if the variable is 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
}