Scala

Scala

Made by DeepSource

Use .isEmpty or .nonEmpty to check if structure is empty SC-P1002

Performance
Major

Scala allows you to use comparison operators such as == and != against List() and Set() to check if a structure is empty or not. However, this method is considered to be in-efficient as doing so instantiates a new and empty structure which is only disposed off by the GC when deemed appropriate, thus causing an additional overhead. Therefore, it is suggested that you use the structures' .isEmpty and .nonEmpty methods to check if the respective structures are empty or not.

Bad practice

// Checking if a `List` is empty or not
if (elements == List()) {
  // List is empty
}

// Checking if a `Set` is empty or not
if (characterSet != Set()) {
  // Set is not empty
}

Recommended

// Checking if a `List` is empty or not
if (elements.isEmpty) {
  // List is empty
}

// Checking if a `Set` is empty or not
if (characterSet.nonEmpty) {
  // Set is not empty
}