为什么这个scala代码编译,恢复的签名是,
def recover[U >: T](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Future[U]然后为什么下面的代码编译。 您可以看到以下代码中的recover不会返回单位。
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?
Why does this scala code compile, The signature of recover is,
def recover[U >: T](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Future[U]then why does below code compile. You can see that recover in below code doesn't return a 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) } } }Also why Await.result(TestRecover.callFailingFunc(Seq()), 20.seconds) doesn't produce stackoverflow because of infinite recursion ?
最满意答案
然后为什么下面的代码编译。 您可以看到以下代码中的恢复不会返回单位。
编译器正在“帮助”你,并进行从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
另外为什么Await.result(TestRecover.callFailingFunc(Seq()),20.seconds)由于无限递归而不会产生stackoverflow?
你没有得到堆栈溢出,因为每次调用failingFunction都会创建一个带有新堆栈的新Future 。
then why does below code compile. You can see that recover in below code doesn't return a Unit.
The compiler is 'helping' you a bit and does an implicit conversion from Future[Unit] to Unit. Effectively compiling it like this.
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) () } }This blog explains is very nicely: 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 ?
You don't get a stack overflow because every call to failingFunction will create a new Future with a new stack.
更多推荐
发布评论