Scala 从 onComplete 返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32334909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 07:32:29  来源:igfitidea点击:

Scala return value from onComplete

scala

提问by krzasteka

How can I structure onComplete in Scala to act in this way:

我如何在 Scala 中构建 onComplete 以这种方式执行:

Fig. 1

图。1

{ 
  var x; 
  if(result.isFailure){
    x = foo() // foo is a future
  }

  if(result.isSuccess){
    x = 5
  }  
  bar(x)
}

I thought I could do it this way:

我以为我可以这样做:

Fig. 2

图2

var x = foo onComplete {
  case Success(x) => 5
  case Failure(t) => foo() //foo is a future
}
bar(x)

But onComplete, onFailure and onSuccess all have Unitas their return type,

但是 onComplete、onFailure 和 onSuccess 都有Unit作为它们的返回类型,

onComplete[U](f: (Try[T]) ? U)(implicit executor: ExecutionContext): Unit
onSuccess[U](pf: PartialFunction[T, U])(implicit executor: ExecutionContext): Unit
onFailure[U](pf: PartialFunction[Throwable, U])(implicit executor: ExecutionContext): Unit

How can I achieve something figure two-ish without using a var?

如何在不使用 var 的情况下实现数字二?

采纳答案by Alexander Tokarev

It is discouraged to block current thread by awaiting a result from a future. Instead, you should call bar() function on processing results of the resultfuture.

不鼓励通过等待未来的结果来阻塞当前线程。相反,您应该调用 bar() 函数来处理result未来的结果。

result map {r =>
   5
} recover {
   case _ => foo()
} map {r => 
   bar(r)
}

回答by Till Rohrmann

You can achieve your goal with

你可以实现你的目标

val x: Future[Int] = foo.map(x => 5).recover{case f => foo()}
// do some more work with your future
x.map(bar(_))

Assuming that foo: Future[_]and foo(): Int.

假设foo: Future[_]foo(): Int.