在 Scala 中不能失败的未来

Future that cannot fail in Scala

Scala中有Future不能失败的概念吗?

我正在将 Future[Result] 转换为 Future[Result],这可能会失败——因此我同时处理 FailureSuccess——转换为 Future[Option[String]],并带有可选错误来自失败或成功状态的消息。到目前为止,还不错。

事情是现在,我想正式(即在类型系统的帮助下)记住这个未来将永远持有 Success 并且我不需要处理失败案例将来。

有没有聪明的方法来做到这一点?

你不能这样做 "with the help of type system" 因为类型系统无法保证 Future 不会失败,即使你保证它不会失败。

考虑一下:

 Future { doStuff(); }
   .recover { case _ => "Failed!" } // Now it always succeeds
   .map { _ => Seq.empty[String].head }  // Now it does not. 

即使您要使任何进一步的转换成为不可能,一旦 Future 被声明为始终成功,那仍然无济于事,因为异常处理程序(或您所做的任何转换原始未来 "always succeeding one") 可能会抛出。

更新: 正如下面的评论所指出的,上面的代码片段是不正确的:.map 的结果与 Future 不同.recover 的结果。然而,这一点是成立的。这是正确的插图:

Future { doStuff }
  .recover { case _ => Seq.empty[String].head }

这不是类型标记的用途吗?

scala> type Tagged[U] = { type Tag = U }
defined type alias Tagged

scala> type @@[T, U] = T with Tagged[U]
defined type alias $at$at

scala> trait OK ; trait Uncertain
defined trait OK
defined trait Uncertain

scala> type Sure[A] = Future[A] @@ OK
defined type alias Sure

scala> type Unsure[A] = Future[A] @@ Uncertain
defined type alias Unsure

scala> val f = Future.successful(42).asInstanceOf[Sure[Int]]
f: Sure[Int] = Future(Success(42))

然后

scala> object X { def p(f: Sure[_]) = "sure" ; def p(f: Unsure[_])(implicit d: DummyImplicit) = "unsure" }
defined object X

scala> X.p(f)
res1: String = sure

当然在地图下不能确定。