在Scala中,我想定义一个Trait,用于在单独的Thread中执行某些代码,如下所示:
val value = RunFuture {
// hard work to compute value...
}
// This was not blocking, so I can do
// some other work until value is computed...
// Eventually, I can use
value.getResult
我写了这个:
object RunFuture
{
def apply[A](block : => A): Future[A] =
{
val future : Future[A] = new Future[A]
val thread : Thread = new Thread {
override def run {
future.result = block
future.done = true
}
}
thread.run
return future
}
}
trait Future[A]
{
var done : Boolean = false
var result : A
def getResult() : A = {
if (done)
result
else
throw new Exception("Wait for it!")
}
def waitForIt() : A = {
while (!done) {
// wait...
}
result
}
}
但是这不会编译,因为trait Future is abstract; cannot be instantiated
如果我尝试像这样实例化它:
val future : Future[A] = new Future[A] {}
而不是
val future : Future[A] = new Future[A]
...当然,编译器会告诉我object creation impossible, since variable result in trait Future of type A is not defined
但是,结果的类型未知。我不能写
result = null
因为这会导致type mismatch;
如何解决这个问题?