【问题标题】:How do you get an object associated with a Future Actor?如何获得与 Future Actor 关联的对象?
【发布时间】:2011-06-06 18:02:15
【问题描述】:

我希望能够访问从生成未来返回的对象

import scala.actors.Future
import scala.actors.Futures._

class Object1(i:Int) {
    def getAValue(): Int = {i}
}

object Test {
    def main( args: Array[String] ) = {
        var tests = List[Future[Object1]]()
        for(i <- 0 until 10) {
            val test = future {
                val obj1 = new Object1(i)
                println("Processing " + i + "...")
                Thread.sleep(1000)
                println("Processed " + i)
                obj1
            }
            tests = tests ::: List(test)
        }
        val timeout = 1000 * 60 * 5  // wait up to 5 minutes
        val futureTests = awaitAll(timeout,tests: _*)

        futureTests.foreach(test => println("result: " + future()))
    }
}

这段代码运行一次的输出是:

Processing 0...
Processing 1...
Processing 2...
Processing 3...
Processed 0
Processing 4...
Processed 1
Processing 5...
Processed 2
Processing 6...
Processed 3
Processing 7...
Processed 4
Processing 8...
Processed 6
Processing 9...
Processed 5
Processed 7
Processed 8
Processed 9
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>
result: <function0>

我试过future().getClass(),输出是

result: class scala.actors.FutureActor

我希望能够访问的是 obj1 对象。

谢谢

布鲁斯

【问题讨论】:

    标签: scala future actor


    【解决方案1】:

    你需要做这样的事情。 awaitAll 的返回是List[Option[Any]]。这意味着每个未来的结果都是一个 Option[Any] 所以你需要一个匹配来获取值并将其转换为getAValue

        futureTests.foreach(test => test match {
            case Some(r) => println("result: " + r.asInstanceOf[Object1].getAValue)
        })
    

    @James Iry致敬

    【讨论】:

    • 实际上,case Some(r: Object1) 是类型安全的,并且不需要强制转换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 2021-10-07
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多