【问题标题】:In Java code, how to properly handle scala future in format of Future[Try[Option[Map[String, Any]]]]在 Java 代码中,如何以 Future[Try[Option[Map[String, Any]]]] 的格式正确处理 scala future
【发布时间】:2020-05-18 23:19:24
【问题描述】:

我需要在 java 代码中调用 scala API。 Scala API 看起来像: def get(id: String): Future[Try[Option[Map[String, Any]]]]

在java代码中,如果一切顺利,如何正确处理Future[Try[Option]]并获取Map?如果有异常,或者Future失败,则重新抛出RuntimeException。

【问题讨论】:

  • Future[Try[_]] 很少有意义
  • 您可以使用github.com/scala/scala-java8-compat 将scala期货转换为Java期货,
  • @cchantep 如果您想调用一个异步返回Try 的函数并跟踪Future 是失败还是成功,这很有意义。
  • 我几乎没有。堆叠此类验证类型只会导致 API 过于复杂。只需将Try 转换为FutureflatMap

标签: java scala future


【解决方案1】:

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
}

更多关于 Futures 和 Await 的信息在 scala 文档中。 https://www.scala-lang.org/api/2.12.9/scala/concurrent/Await$.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 2020-07-16
    相关资源
    最近更新 更多