简体   繁体   中英

Why the result type of unwrapping future via for comprehension is Future?

My code:

val f1 = Future[String] { "ok1" }
val fRes: Future[String] = for { r <- f1 } yield r

I expect fRes to be a String, but I get a Future[String] . Why?

I don't want to use Await.result .

val fRes = for { r <- Await.result(f1, Duration(1, TimeUnit.SECONDS)) } yield r

The combination of for and yield does not "unwrap" the Future . In practice that is a good thing.

So every kind of Option , Try , List or as the fancy functional people call it Applicative Functor keeps it's type this way.

Due to this property you can code inside the for { <- } as if the code was "unwrapped" but only because it is made sure that outside of the code the things stays wrapped.

It may be clearer when on looks at what a for-comprehension does under the hood. It is syntactic sugar for chained map and flatMap operations.

val x: Option[_] = Some(5).map{ i => 
  // i is "unwrapped" here 
  (i * i).toString  
}

val x: Option[_] = for {
  i <- Some(5)
} yield i.toString // i unwrapped for the for comprehension but will keep Option type

If you want to access the future value at the end and do something in a synchronuous program flow with it you only have to options

As @Robert Udah suggest you can use onComplete and have a callback function or you have to use Await .

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