如何从Scala Future onComplete/onSuccess获得价值 [英] How to get out value from Scala Future onComplete/onSuccess
本文介绍了如何从Scala Future onComplete/onSuccess获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码结构如下.这只是复制高级结构的示例.
I have a high level structure of my code as follows. This is just an example replicating the high level structure.:-
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(),但这不是我想要的.
So my requirement is this:- I need the string from the addAgeCurse() method. Now I know some off you may suggest to pass the future value LongProcessingOpForAge() as such to main() but that is not what I want here.
问题:
- 获取字符串并将其传递给main()的最干净方法是什么. (通过干净,我的意思是不涉及使用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
转换将来的值.
That's the easy idiom to block for your answer. The main thread won't exit until it has it. Use map
to transform a future value.
这篇关于如何从Scala Future onComplete/onSuccess获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文