Consider rewriting
arr.filter().head
as arr.filter().headOption
21 }
22 }
23
24 def pickFirst1(arr: Array[Int], criteria: Int => Boolean): Int = arr.filter(criteria).head25 def pickFirst2(arr: Array[Int], criteria: Int => Boolean): Option[Int] =
26 arr.filter(criteria).headOption
27 def pickInAnOrder(arr: Array[Int], criteria: Int => Boolean): Array[Int] =
Description
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
}