Use scala.actors.Future:
import actors._
def asyncify[A, B](f: A => B): A => Future[B] = (a => Futures.future(f(a)))
def sleepFor(seconds: Int) = {
Thread.sleep(seconds * 1000)
seconds
}
val asyncSleepFor = asyncify(sleepFor)
val future = asyncSleepFor(5)
println("waiting...")
println("future returns %d".format(future()))
The overloaded "asyncify", which accepts a function with several parameters, remains as an exercise.
One caveat is exception handling. A function that is "asynchronized" should handle all exceptions, catching them. The behavior for exceptions excluded from the function is undefined.
source
share