小编ozm*_*zma的帖子

在scala中将Try转换为Future,并将recoverWith转换为Future

[编辑]

被问到时我是新手.这就是答案:

Future.fromTry(Try( 1/0 ))
Run Code Online (Sandbox Code Playgroud)

其他值得了解的事情(可能会错过 - 在检查时引导我):

Future.successful( 1/0 )
Run Code Online (Sandbox Code Playgroud)

会抛出一次.Future.successful和Future.failure不仅是创建Future的便捷方式,它们还跳过执行上下文循环并按顺序进行求值.


[原始问题]

我有一个Try抛出异常.我想要Try成为一个Future我能够做到的recoverWith.

如果你不知道,请不要猜.

问题是,如何TryFuture不处理任何异常的情况下转换为Try(仅在未来的恢复中)?

请注意,需要Await来测试您未来的结果

代码示例演示了我的想法,但是一旦达到它就会抛出(new RuntimeException("-------failed-------")就是我得到的)

val t = Try(throw new RuntimeException("my"))

val resF : Future[String] = if (t.isSuccess)
  Future.successful(t.get)
else
  Future.failed(new RuntimeException("-------failed-------"))

val resFWithRecover = resF.recoverWith{
  case NonFatal(e) =>
    Future.successful("recoveredWith")
}
Await.result(resFWithRecover, Duration("5s"))
Run Code Online (Sandbox Code Playgroud)

concurrency scala

9
推荐指数
1
解决办法
7280
查看次数

如何在scala中展平未来 - "val _2flat:Future [Option [Future [List [Long]]]]

我有这些数据:

val _2BeFlat: Future[Option[Future[List[Long]]]] = ...
Run Code Online (Sandbox Code Playgroud)

我需要:

val flat: Future[Option[List[Long]]] = ...
Run Code Online (Sandbox Code Playgroud)

有办法吗?

scala nested future

1
推荐指数
1
解决办法
1080
查看次数

标签 统计

scala ×2

concurrency ×1

future ×1

nested ×1