0

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?

Philipp Moers
  • 570
  • 3
  • 15
  • 3
    `var result : A = _`. Also, why not just use a normal `scala.concurrent.Future`? It can do the same things but with better control where to execute the concurrent code and how to wait for its completion. – Kolmar Dec 01 '15 at 16:42
  • Thank you, that works. I did not know I could use an underscore like that. Related questions are [here](http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala) and [here](http://stackoverflow.com/questions/22363950/assign-a-underscore-to-a-variable-what-is-the-underscore-doing) – Philipp Moers Dec 01 '15 at 21:43
  • @Kolmar I do not use `scala.concurrent.Future` because I am learning Scala and this is an exercise. – Philipp Moers Dec 01 '15 at 21:45
  • This is not a good example for learning scala syntax, I see there are more problems than advantages, at least need to understand why not need to use `var` shared through different threads. I recommend you split learning scala & multi-threding concepts. – Yuriy Dec 02 '15 at 10:07

0 Answers0