【发布时间】:2017-08-02 10:03:05
【问题描述】:
我的代码具有如下高级结构。这只是一个复制高层结构的例子。:-
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() ,但这不是我想要的。
问题:
- 获取字符串并将其传递给 main() 的最简洁方法是什么。 (通过 clean ,我的意思是不涉及使用等待 x 持续时间,因为我想避免任何手动干预。)
谢谢
【问题讨论】:
-
你将不得不等待未来在某个地方完成。您可以更改函数以返回未来并在主函数中等待,或者在函数中等待。
-
或者撰写而不是等待
-
@cchantep,如何在这里撰写帮助。您能否提供更多信息。谢谢
-
试图从
Future中“提取”纯/同步值正在消除任何并发/并行/线程优势。而是继续“在内部”工作 -
是的,不要出去。留在!也不要
println,这只会弄乱他们的终端。