filter().headOption
as find()
SC-P1006The scala analyzer has determined that this collection method chain can be simplified into a single call to find()
.
Scala collections such as List
and ArrayBuffer
implement a number of processing methods -
1. .filter
- allows you to select elements from your collection based on the condition specified.
2. .find
- returns the first element that satisfies your condition as an Option
.
3. .headOption
- returns the first element from your collection as an Option
.
While .find
behaves in the exact same manner as .filter().headOption
, it performs slightly better as it terminates after finding the first element that satisfies your condition while .filter
continues to iterate through the entire collection. It is therefore suggested that you rewrite .filter().headOption
as .find
.
val firstEven = nums.filter(x => x % 2 == 0).headOption
val firstEven = nums.find(x => x % 2 == 0)