Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 在recoverpartial方法中调用future_Scala_Future - Fatal编程技术网

Scala 在recoverpartial方法中调用future

Scala 在recoverpartial方法中调用future,scala,future,Scala,Future,我有分部方法defaultRecover帮助从异常中恢复: def getName(length: Int): Future[String] = { if (length > 0) Future.successful("john") else Future.failed(new RuntimeException("failed")) } def defaultRecover: PartialFunction[Throwable, Str

我有分部方法
defaultRecover
帮助从异常中恢复:

  def getName(length: Int): Future[String] = {
    if (length > 0)
      Future.successful("john")
    else
      Future.failed(new RuntimeException("failed"))
  }

  def defaultRecover: PartialFunction[Throwable, String] = {
    case _ => "jane"
  }

  // easy and working
  val res = getName(0) recover {
    defaultRecover
  }
现在问题来了。我定义了第二种恢复方法
emergencyRecover
,我想根据另一个调用的结果选择使用哪种恢复方法-
isEmergency()

但是我得到了类型不匹配。如何实现这种错误处理?我需要使用另一种方法来恢复吗?

正如我常说的,客户是您的朋友。您可以使用
recoverWith

另外,请记住,它接收一个部分函数,因此您必须执行以下操作:

val res = getName(0) recoverWith {
  case e => isEmergency() map {
    case false => defaultRecover(e)
    case true  => emergencyRecover(e)
  }
}

您只需使用recoverWith即可:

  val res2 = getName(0) recoverWith {
    case _ =>  isEmergency().map {
      case false => "jane"
      case true => "arnold"
    }
  }
  val res2 = getName(0) recoverWith {
    case _ =>  isEmergency().map {
      case false => "jane"
      case true => "arnold"
    }
  }