从理解中恢复的更好语法

时间:2014-09-08 20:23:19

标签: scala future for-comprehension

我有许多函数可以返回未来,这是一个理解的结果,但我需要在出路时从一些可能的失败中恢复。标准语法似乎将for comprehension捕获为中间结果,如下所示:

def fooBar(): Future[String] = {
  val x = for {
    x <- foo()
    y <- bar(x)
  } yield y
  x.recover {
    case SomeException() => "bah"
  }
}

我找到的最好的替代方法是用括号括起整体来理解:

def fooBar(): Future[String] = (for {
  x <- foo()
  y <- bar(x)
} yield y).recover {
  case SomeException() => "bah"
}

这似乎是一种捷径,而不是语法上的改进,所以我想知道是否有更好的方法将恢复编织为理解?

2 个答案:

答案 0 :(得分:9)

一些支撑调整有帮助,尽管有些人更喜欢括号而不是用于多线表达的parens:

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
}

如果你那样摆动。

答案 1 :(得分:1)

这样做,

def fooBar(): Future[String] = { foo flatMap bar recover { case someException => ...}}

'bar'将对'foo'返回的Future执行操作并生成所需的Future,并且恢复块可以像往常一样处理异常。