简体   繁体   中英

Scala Option with fold operation

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?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM