将Scala Future转换为Java Future [英] Convert scala future to java future
问题描述
我有一个包含方法的生成的Java接口:
I have a generated java interface containing a method:
public Future<?> getCustomersAsync(AsyncHandler<Customer> asyncHandler);
我想使用Akka来实现它.我写了以下内容:
I want to implement it using Akka. I wrote following:
override def getCustomerAsync(asyncHandler: AsyncHandler[Customer]): Future[_] = {
myActorRef.ask(GetCustomer, system.actorOf(Props[Responder]))
}
问题在于ask
返回scala.concurrent.Future[Any]
,并且该方法必须返回java.util.concurrent.Future[?]
:
The issue is that ask
returns scala.concurrent.Future[Any]
and the method must return java.util.concurrent.Future[?]
:
Error:(33, 17) type mismatch;
found : scala.concurrent.Future[Any]
required: java.util.concurrent.Future[?]
myActorRef.ask(GetCustomer, system.actorOf(Props[Responder]))
^
我该如何进行转换?
推荐答案
将它们转换是不切实际的,因为scala Future
不提供中断功能或其他任何取消机制.因此,没有直接的充分证明方式可以通过中断或通过Future中的方法调用来取消未来.
Well its not practical to convert them, because scala Future
do not provide functionality to interrupt or any other mechanism for cancellation. So there is no direct full-proof way to cancel a future via interruption or otherwise via method call in Future.
因此,最简单的解决方案是:如果不需要取消,则为:
So the simplest solution can be if cancellation is not desired would be:
def convert[T](x:Future[T]):java.util.concurrent.Future[T]={
new concurrent.Future[T] {
override def isCancelled: Boolean = throw new UnsupportedOperationException
override def get(): T = Await.result(x, Duration.Inf)
override def get(timeout: Long, unit: TimeUnit): T = Await.result(x, Duration.create(timeout, unit))
override def cancel(mayInterruptIfRunning: Boolean): Boolean = throw new UnsupportedOperationException
override def isDone: Boolean = x.isCompleted
}
}
但是如果您仍然需要cancel
,则有缺陷的修补程序将显示为
But in case if you still need cancel
, a handicapped fix would be as shown
此处.但是我不推荐它,因为它摇摇欲坠
here. But I wouldn't recommend it though as its shaky
这篇关于将Scala Future转换为Java Future的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!