从a理解中恢复的更好语法 [英] A better syntax for recovery from a for comprehension
问题描述
我有许多函数可以返回将来,这是a理解的结果,但是我需要在出路时从一些可能的故障中恢复过来.标准语法似乎将for理解捕获为中间结果,如下所示:
I have a number of functions that return a future that is the result of a for comprehension, but i need to need to recover from some possible failures on the way out. The standard syntax seems to capture the for comprehension as an intermediate results like so:
def fooBar(): Future[String] = {
val x = for {
x <- foo()
y <- bar(x)
} yield y
x.recover {
case SomeException() => "bah"
}
}
我发现的最好的替代方法是将整个内容包装在括号中以供理解:
The best alternative to I've found is to wrap the whole for comprehension in parentheses:
def fooBar(): Future[String] = (for {
x <- foo()
y <- bar(x)
} yield y).recover {
case SomeException() => "bah"
}
与语法改进相比,这似乎主要是捷径,所以我想知道是否有更好的方法将恢复用于理解?
This mostly seems like a shortcut than an improvement in syntax, so I'm wondering if there is a better way to weave recovery into for comprehensions?
推荐答案
一些大括号调整会有所帮助,尽管有些人更喜欢使用大括号而不是括号来表示多行表达式:
Some brace adjustment helps, though some people prefer braces instead of parens for a multiline expression:
scala> def f = (
| for {
| x <- foo;
| y <- bar(x)
| } yield y
| ) recover {
| case _: NullPointerException => -1
| }
f: scala.concurrent.Future[Int]
如果您不喜欢
scala> foo flatMap bar recover { case _: NullPointerException => -1 }
res9: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@3efe7086
您可以使用所有语法:
object Test extends App {
import concurrent._
import duration.Duration._
import ExecutionContext.Implicits._
type ~>[A, B] = PartialFunction[A, B]
type NPE = NullPointerException
class `recovering future`[A, R >: A](val f: Future[A], val pf: Throwable ~> R) {
def map[B >: A <: R](m: A => B) = new `recovering future`[B, R](f map m, pf)
def flatMap[B >: A <: R](m: A => Future[B]) = new `recovering future`[B, R](f flatMap m, pf)
def recovered: Future[R] = f recover pf
}
object `recovering future` {
implicit def `back to the future`[A, R >: A](x: `recovering future`[A, R]): Future[R] = x.recovered
}
implicit class `inline recoverer`[A](val f: Future[A]) {
def recovering[B >: A](pf: Throwable ~> B) = new `recovering future`(f, pf)
}
def f = Future(8)
def g(i: Int) = Future(42 + i)
def e(i: Int): Future[Int] = Future((null: String).length)
未经修饰:
for {
x <- f
y <- g(x)
} Console println y // 50
并内联恢复:
def compute: Future[Int] =
for {
x <- f recovering { case _: NPE => -1 }
y <- g(x)
} yield y
Console println (Await result (compute, Inf)) // 50
或显示失败的情况:
def fail: Future[Int] =
for {
x <- f recovering { case _: NPE => -1 }
y <- e(x)
} yield y
Console println (Await result (fail, Inf)) // -1
}
如果你那样摇摆.
这篇关于从a理解中恢复的更好语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!