如何从Scala Future onComplete / onSuccess中获取价值

时间:2017-08-01 21:03:52

标签: scala future

我的代码的高级结构如下所示。这只是复制高级结构的一个例子。: -

import scala.concurrent.Future


class FutureReturnsAValue extends PersonAgeModifier {
  def main(args: Array[String]) {

    val jhonObj = Person("Jhon", 25)

    val punishmentResult = addAgeCurse(jhonObj)
    println("The punishment result for Jhonny is " + punishmentResult)

  }

  def addAgeCurse(person: Person): String = {

    val oldAge = person.age
    val futureAge = LongProcessingOpForAge(person)
    futureAge.onSuccess {

      newAge =>

        if (newAge = oldAge + 5) {
          "screw the kiddo, he aged by 5 years" // somehow return this string
        }

        else {
          "lucky chap, the spell did not affect him" // somehow return this string
        }
    }

  }
}

class PersonAgeModifier {

  def LongProcessingOpForAge(person: Person): Future[Int] = {
    Future.successful {
      person.age + 5
    }
  }
}


case class Person
(
  val name: String,
  var age: Int

)

object Person {
  def apply(name: String, age: Int) = new Person(name, age)

}

所以我的要求是: - 我需要addAgeCurse()方法中的字符串。现在我知道一些你可能会建议将未来的值LongProcessingOpForAge()传递给main(),但这不是我想要的。

问题:

  1. 获取字符串并将其传递给main()的最简洁方法是什么? (通过干净,我的意思是不涉及使用等待x持续时间的东西,因为我想避免任何人工干预。)
  2. 由于

1 个答案:

答案 0 :(得分:0)

也许你要求:

scala> import concurrent._, ExecutionContext.Implicits._
import concurrent._
import ExecutionContext.Implicits._

scala> def f = Future(42)
f: scala.concurrent.Future[Int]

scala> def g = f.map(_ + 1)
g: scala.concurrent.Future[Int]

scala> :pa
// Entering paste mode (ctrl-D to finish)

object Main extends App {
  for (i <- g) println(i)
}

// Exiting paste mode, now interpreting.

defined object Main

scala> Main main null
43

这是阻止你回答的简单习惯用语。主线程不会退出,直到它拥有它。使用map转换未来值。