Reputation: 4004
I am trying to use fold
or map
operation instead of match
for Option
.
I have a Option val ao: Option[String] = xxxx
and a function f: (String => Future[Option[T]])
If I do pattern matching is:
ao match {
case Some(t) => f(t)
case None => Future.successful(None)
}
if I do map is:
ao map f getOrElse Future.successful(None)
But when I do fold, I got some following compiler errors:
ao.fold(Future.successful(None))(t => f(t))
about complaining expression Future[Option[T]] doesn't confirm to Future[None.type]
So why map works here but fold not, did I miss something here?
Upvotes: 3
Views: 3253
Reputation: 5449
The reason for this is that Scala is trying to derive the return type None.type
which is kind of like Nil
for lists in the sense that only one object (None
) exists and is upcast in all situations because it is Option[Nothing]
. To get around this, you should explicitly define the types.
Here's the Scala doc for fold
:
fold[B](ifEmpty: ⇒ B)(f: (A) ⇒ B): B
Returns the result of applying f to this scala.Option's value if the scala.Option is nonempty. Otherwise, evaluates expression ifEmpty.
The compiler thinks [B]
is None.type
. so try calling it this way :
ao.fold[Future[Option[T]]](Future.successful(None))(t => f(t))
or calling it with a type ascription :
ao.fold(Future.successful(None: Option[T]))(t => f(t))
Upvotes: 10