scala - 成功和失败函数参数 Scala 模式

标签 scala closures anonymous-function function-parameter

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 方法指定失败时的行为(还有 onCompleteonSuccess):

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,因此您可以使用 mapflatMap 之类的东西创建异步操作的管道:

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/

相关文章:

scala - Scala中的ClassCastException

JavaScript img onLoad 和闭包 - 为什么这段代码会触发无限循环?

ios - 如何在完成处理程序中传递数据

c# - 取消订阅事件

scala - 如何替换 Vector 列中的空值?

Scala:将 Set 传递给 set 的 map 函数是什么意思

scala - 将包含选项卡的代码粘贴到 scala repl 中

design-patterns - 这种带有闭包的模式有名字吗?

javascript - Java Nashorn - 如何在 Java 中定义接受匿名函数作为参数的 JavaScript 函数?

javascript - 在循环中的多个匿名异步函数中保持不同变量的状态