Search code examples
scalafolding

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


I'm trying to fold over a list of Options in order return the first(or last) Some value or None if there aren't any Some values.

scala> val opts = List(None, Some(1), None, Some(2), None)
opts: List[Option[Int]] = List(None, Some(1), None, Some(2), None)

scala> opts foldLeft(None)((a,io) => a match { case None => io; case Some(i) =>
a})
<console>:9: error: object None does not take parameters
              opts foldLeft(None)((a,io) => a match { case None => io; case Some
(i) => a})
                                 ^

Not sure what I'm doing wrong. Also there is probably a way to do this simpler using a higher order function but nothing from here caught my eye.


Solution

  • 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.