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

Hak*_*kar 2 closures scala anonymous-function function-parameter

Scala中是否有成功和失败关闭的替代模式?

这个约定与node.js库通常做的类似,但是我只是想知道在Scala中是否有另一种方法可以做到这一点.

例如:

def performAsyncAction(n: BigInt,
                success: (BigInt) => Unit,
                failure: FunctionTypes.Failure): Unit = {
Run Code Online (Sandbox Code Playgroud)

然后调用该函数

performAsyncAction(10,
         {(x: BigInt) => 
              /* Code... */
         }, 
         {(t: Throwable) => 
              e.printStackTrace()
         })
Run Code Online (Sandbox Code Playgroud)

谢谢

dhg*_*dhg 8

听起来你想要一个Future.请参阅此处的AKKA实施.

A 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"
Run Code Online (Sandbox Code Playgroud)

您可以使用该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"
Run Code Online (Sandbox Code Playgroud)

但是,最好的部分是,Futures为单子,这样你就可以创建使用像异步操作的管道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"
Run Code Online (Sandbox Code Playgroud)

或者将它们用于理解:

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"
Run Code Online (Sandbox Code Playgroud)