Scala

Scala

Made by DeepSource

Potential NoSuchElementException in accessing filtered elements SC-R1006

Bug risk
Critical

filter allows you to select elements from your collection based on the condition specified. However, accessing these elements directly via head or last may result in the throwing of NoSuchElementException if no elements satisfy the specified condition. Therefore, it is recommended that you use headOption and lastOption respectively to access these elements.

Bad practice

val myElements  = numbers.filter(x => x % 2 == 0 && x > 5)
val firstElement = myElements.head
val lastElement = myElements.last

Recommended

val myElements  = numbers.filter(x => x % 2 == 0 && x > 5)
val firstElement = myElements.headOption
val lastElement = myElements.lastOption
}

References