In Scala, I want to define a Trait for executing some code in a separate Thread like this:
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
I wrote this:
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
}
}
But this does not compile, since trait Future is abstract; cannot be instantiated
If I try to instantiate it like this:
val future : Future[A] = new Future[A] {}
instead of
val future : Future[A] = new Future[A]
... of course, the compiler tells me object creation impossible, since variable result in trait Future of type A is not defined
However, the type of result is unknown. I can not write
result = null
since that leads to a type mismatch;
How to solve this problem?