gpt4 book ai didi

scala - 从异常中恢复,scala Future

转载 作者:行者123 更新时间:2023-12-01 13:46:23 24 4
gpt4 key购买 nike

为什么这个scala代码可以编译,恢复的签名是,

def recover[U >: T](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Future[U]

那为什么下面的代码可以编译。您可以看到下面代码中的 recover 没有返回一个 Unit。

 object TestRecover {

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

def failingFunction(input: Seq[String]): Future[Unit] = {
Future {
if (input.isEmpty) throw new Exception("Cannot be empty")
else ()
}
}

def callFailingFunc(input: Seq[String]): Future[Unit] = {
failingFunction(input).recover {
case _ =>
//Not returning Unit here, but Future[Unit]. Shouldn't type checker fail this ?
callFailingFunc(input.reverse)
}
}
}

另外,为什么 Await.result(TestRecover.callFailingFunc(Seq()), 20.seconds) 由于无限递归而不会产生 stackoverflow?

最佳答案

then why does below code compile. You can see that recover in below code doesn't return a Unit.

编译器会稍微“帮助”您,并执行从 Future[Unit]Unit 的隐式转换。像这样有效地编译它。

def callFailingFunc(input: Seq[String]): Future[Unit] = {
failingFunction(input).recover {
case _ =>
//Not returning Unit here, but Future[Unit]. Shouldn't type checker fail this ?
callFailingFunc(input.reverse)
()
}
}

这个博客解释的很好:http://blog.bruchez.name/2012/10/implicit-conversion-to-unit-type-in.html

Also why Await.result(TestRecover.callFailingFunc(Seq()), 20.seconds) doesn't produce stackoverflow because of infinite recursion ?

您不会出现堆栈溢出,因为每次调用 failingFunction 都会创建一个带有新堆栈的新 Future

关于scala - 从异常中恢复,scala Future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35776802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com