代码之家  ›  专栏  ›  技术社区  ›  hawkeye

我怎样才能从未来的斯卡拉中获得价值呢?

  •  0
  • hawkeye  · 技术社区  · 7 年前

    我有以下代码:

    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
    

    重点是-在未来似乎没有任何价值是为了理解或被映射。

    我的问题是: 我怎样才能从未来的斯卡拉中获得价值呢?

    笔记:

    这是我的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"
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   emran    7 年前

    虽然我对斯卡拉的未来知之甚少,但我想你只是错过了 .start .unsafeStart 开始运行 Future .

    即使你用 开始 ,您需要用类似于 scala.io.StdIn.readLine("press enter to exit") .

    另一种选择是 .run unsafePerformSync 它将阻塞并等待结果。

    val res = summed.run
    println(res) // currently Unit because it yields println
    println("done")
    

    这将产生副作用,运行未来并返回结果。

    我是通过查看 scalaz.concurrent.Future .

    你应该注意到在实践中人们使用 Task 因为错误处理,除非您正在编写库(如源代码中所述)。

        2
  •  0
  •   ziggystar    6 年前

    如果您持有类型的值 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