I am in the process of writing a small scala wrapper around a java library.
The java library has an object QueryExecutor exposing 2 methods:
Another, slightly shorter solution:
implicit class ListenableFutureDecorator[T](val f: ListenableFuture[T]) extends AnyVal {
def asScala(implicit e: Executor): Future[T] = {
val p = Promise[T]()
f.addListener(() => p.complete(Try(f.get())), e)
p.future
}
}
The second option is best, it keeps everything asynchronous. but... you can do one better and abstract the solution into a reusable pattern:
implicit class RichListenableFuture[T](lf: ListenableFuture[T]) {
def asScala: Future[T] = {
val p = Promise[T]()
Futures.addCallback(lf, new FutureCallback[T] {
def onFailure(t: Throwable): Unit = p failure t
def onSuccess(result: T): Unit = p success result
})
p.future
}
}
You can then simply call:
executor.asyncExecute(query).asScala