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



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

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(( 的最干净方法是什么。(通过清洁,我的意思是不涉及使用 wait x 持续时间的东西,因为我想避免任何手动干预。

谢谢

也许你要求:

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转换未来值。

最新更新