你如何得到一个与未来演员相关的对象?

时间:2011-01-10 19:42:36

标签: scala future actor

我希望能够访问从产生未来的

中返回的对象
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对象。

由于

布鲁斯

1 个答案:

答案 0 :(得分:2)

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

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

提示@James Iry