[英]In Java code, how to properly handle scala future in format of Future[Try[Option[Map[String, Any]]]]
我需要在java代码中调用scala API。 scala API 看起来像: def get(id: String): Future[Try[Option[Map[String, Any]]]]
java代码中,如果一切顺利,如何正确处理Future[Try[Option]]并获取Map? 如果有异常,或者 Future 失败,则重新抛出 RuntimeException。
Future[Try[Option[Map[String, Any]]]]
是一种矫枉过正,因为对未来的评估结果看起来已经是一种尝试。 所以,让你有这样的未来,那么最简单的方法 - 是使用 Await.result 然后切入类型堆栈:
Future<Try<Option<Map<String, Any>>>> yourFuture = yourFunc(...);
scala.concurrent.duration.FiniteDuration timeout = new FiniteDuration(..., ...);
/*simplest, but not the best way of doing so, it will throw an exception if something goes wrong, you probably want to wrap this in try-catch block in real code*/
Try<Option<Map<String, Any>>> result = Await.result<Try<Option<Map<String, Any>>>>(yourFuture, timeout);
if(result.isSuccess()){
Option<Map<String, Any>> option = result();
if(option.nonEmpty()){
Map<String, Any> mapYouNeed = option.get();
} else {
// throw your exception
}
} else {
// throw your exception
}
scala 文档中有关 Futures 和 Await 的更多信息。https://www.scala-lang.org/api/2.12.9/scala/concurrent/Await $.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.