Scala 中有成功和失败闭包的替代模式吗?
这个约定没有任何问题,与 Node.js 库通常所做的类似,但我只是想知道在 Scala 中是否有另一种方法可以做到这一点。
例如:
def performAsyncAction(n: BigInt,
success: (BigInt) => Unit,
failure: FunctionTypes.Failure): Unit = {
然后调用该函数
performAsyncAction(10,
{(x: BigInt) =>
/* Code... */
},
{(t: Throwable) =>
e.printStackTrace()
})
谢谢
最佳答案
听起来你想要一个 future
。请参阅 AKKA 实现 here .
Future
是一种函数式构造,可让您指定要异步执行的代码块,然后您可以在完成后获取结果:
import akka.actor.ActorSystem
import akka.dispatch.Await
import akka.dispatch.Future
import akka.util.duration._
implicit val system = ActorSystem("FutureSystem")
val future = Future {
1 + 1
}
val result = Await.result(future, 1 second)
println(result) // prints "2"
您可以使用 onFailure
方法指定失败时的行为(还有 onComplete
和 onSuccess
):
val future = Future {
throw new RuntimeException("error")
}.onFailure {
case e: RuntimeException => println("Oops! We failed with " + e)
}
// will print "Oops! We failed with java.lang.RuntimeException: error"
但最好的部分是,Future
是 Monad,因此您可以使用 map
和 flatMap
之类的东西创建异步操作的管道:
val f1 = Future { "hello" }
val f2 = f1.map(_ + " world")
val f3 = f2.map(_.length)
val result = Await.result(f3, 1 second)
println(result) // prints "11"
或者在 for 推导式中使用它们:
val f1 = Future { "hello" }
val f2 = Future { " " }
val f3 = Future { "world" }
val f4 =
for (
a <- f1;
b <- f2;
c <- f3
) yield {
a + b + c
}
val result = Await.result(f4, 1 second)
println(result) // prints "hello world"
关于scala - 成功和失败函数参数 Scala 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11839204/