Scala

Scala

Made by DeepSource

Consider using .collectFirst() over .collect().headOption SC-P1011

Performance
Major

The collect() method collects the elements that satisfy the specified predicate. Chaining it with headOption returns the first element from this collection. However, the collect operation here is inefficient as elements except the first one are discarded without use.

It is recommended that you instead use .collectFirst() as:

  1. Iteration is terminated as soon as the first element that satisfies the predicate is found, and,

  2. No resources are allocated for the intermediate buffer.

Bad practice

nums.collect(_ % 2 == 0).headOption

Recommended

nums.collectFirst(_ % 2 == 0)