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.
Maybe this can solve your problem - the first element:
And the last element:
flatten
method will unbox allOption
values in the list and drop allNone
values.headOption
/lastOption
will return eitherSome
for the first/last element in the list orNone
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:
Unfortunately, we cannot use
flatten
here as this will return a genericIterable[Int]
and noOption
, so we have to chose the longer idiomflatMap(identity)
.Edit: As dave noticed:
would be even better.
Starting
Scala 2.9
, you can usecollectFirst
to extract the first defined option:this will stop iterating at the first defined
Option
and avoids flattening the wholeList
before looking for its head.Starting
Scala 2.13
you can usefindLast
, which is the reverse offind
(while waiting for a possiblecollectLast
?)There are better ways to do it, but to answer the question as posed, you have two problems
1) You are missing the
.
followingopts
. You can only use infix notation to converta.m(b)
toa m b
. The foldLeft method is of the forma.m(b)(c)
. So either write it like that, or include parentheses(a m b)(c)
.2) You need to parameterize
None
as anOption[Int]
: it's being interpreted here as theNone
object, rather than the value of anOption[Int]
instance.So this will work:
Why go to such trouble?