Folding over a list of Options to Find First or Last Some

Maybe this can solve your problem - the first element:

opts.flatten.headOption

And the last element:

opts.flatten.lastOption

flatten method will unbox all Option values in the list and drop all None values. headOption/lastOption will return either Some for the first/last element in the list or None if list is empty.


tenshi’s answer is pretty straightforward but for long lists it will attempt to flatten everything as it isn’t lazy. (I think view won’t help us here either but I’m not quite sure.)

In that case, you could use:

opts.dropWhile(_.isEmpty).headOption.flatMap(identity)

Unfortunately, we cannot use flatten here as this will return a generic Iterable[Int] and no Option, so we have to chose the longer idiom flatMap(identity).

Edit: As dave noticed:

opts.find(_.isDefined).flatMap(identity)

would be even better.


There are better ways to do it, but to answer the question as posed, you have two problems

1) You are missing the . following opts. You can only use infix notation to convert a.m(b) to a m b. The foldLeft method is of the form a.m(b)(c). So either write it like that, or include parentheses (a m b)(c).

2) You need to parameterize None as an Option[Int]: it's being interpreted here as the None object, rather than the value of an Option[Int] instance.

So this will work:

opts.foldLeft(None: Option[Int])(
  (a,io) => a match { case None => io; case Some(i) => a } )

Tags:

Scala

Folding