【问题标题】:How do I get the value out of a Future in Scalaz?如何从 Scalaz 中的 Future 中获取价值?
【发布时间】:2019-02-07 17:08:33
【问题描述】:

我有以下代码:

package functorapplication

import scalaz._
import Scalaz._
import scalaz.concurrent.Future

object FunctorApplication2 extends App {

  val f1 = Future(3)//(ec)
  val f2 = Future(4)//(ec)
  val f3 = Future(5)//(ec)
  val calculate = (a: Int) => (b: Int) => (c: Int) => a + b + c
  val area = f1 <*> (f2 <*> (f3 <*> Future(calculate)))//(ec))) // Future(12)

  //println(area)//BindSuspend(scalaz.concurrent.Future$$Lambda...
  println("starting")
  val summed = for {
    a <- area
  } yield {
    println(a)
  }
  area.map(value => println(value))

  //println(summed)//Suspend(scalaz.concurrent.Future$$Lambda...
  println("done")

}

这给出了以下结果:

starting
done

关键是 - 在未来似乎没有任何价值在 for 理解或被映射。

我的问题是:如何从 Scalaz 中的 Future 中获取价值?

注意事项:

这是我的 scala 版本

scalaVersion := "2.12.5",

这是我的 scalaz 版本

  "org.scalaz" %% "scalaz-core" % "7.2.26",
  "org.scalaz" %% "scalaz-concurrent" % "7.2.26",
  "org.scalaz" %% "scalaz-effect" % "7.2.26",
  "org.scalaz" %% "scalaz-iteratee" % "7.2.26"

【问题讨论】:

    标签: scala future scalaz


    【解决方案1】:

    如果您持有Future[A] 类型的值,那么您有资格在未来某个时间获得

    • A 类型的值
    • 或者错误,表示为Throwable类型的值。

    因此,未来代表了潜在的未来价值。获得未来值的唯一已知方法是等待它。

    import scala.concurrent._
    import scala.concurrent.ExecutionContext.Implicits.global
    import scala.concurrent.duration._
    
    val f1 = Future(3)//(ec)
    val f2 = Future(4)//(ec)
    val f3 = Future(5)//(ec)
    
    val calculate = (a: Int) => (b: Int) => (c: Int) => a + b + c
    
    val area: Future[Int] = for {
      v1 <- f1 
      v2 <- f2 
      v3 <-f3 
    } yield calculate(v1)(v2)(v3)
    
    println("starting")
    
    println("adding future side effect")
    //this happens in the future
    val withSideEffect = area.map(value => println("side-effect: " + value))
    
    println("awaiting now")
    //now, let's wait
    println("Await: " + Await.ready(withSideEffect, Duration.Inf).value)
    
    println("done")
    

    打印出来:

    starting
    adding future side effect
    awaiting now
    side-effect: 12
    Await: Some(Success(()))
    done
    

    【讨论】:

      猜你喜欢
      • 2022-10-24
      • 1970-01-01
      • 2014-05-29
      • 2020-01-22
      • 2020-02-24
      • 1970-01-01
      • 2020-04-04
      • 2019-07-01
      • 1970-01-01
      相关资源
      最近更新 更多