NoSuchElementException
in accessing filtered elements SC-R1006filter
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.
val myElements = numbers.filter(x => x % 2 == 0 && x > 5)
val firstElement = myElements.head
val lastElement = myElements.last
val myElements = numbers.filter(x => x % 2 == 0 && x > 5)
val firstElement = myElements.headOption
val lastElement = myElements.lastOption
}