pathikrit pathikrit - 1 month ago 6
Scala Question

Find the first defined item in a collection in Scala

Given a collection,

coll: C[A]
and a function
f: A => Option[B]
, what's the idiomatic way in Scala to get the first item in
coll
for which
f
is defined without evaluating the whole collection?

Here's my intended signature:

def findFirstDefined[A, B](coll: Traversable[A])(f: A => Option[B]): Option[B]


A naive approach like
coll.flatMap(f).headOption
would evaluate the whole collection. We can possibly do
coll.view.flatMap(f).headOption
or
coll.collectFirst(Function.unlift(f))
but is there something else either in the standard library or in functional programming literature or in scalaz/cats that would let me do this?

Answer

As mentioned in the question, this seems like a decent solution:

def findFirstDefined[A, B](coll: Traversable[A])(f: A => Option[B]): Option[B] = 
  coll.collectFirst(Function.unlift(f))
Comments