【问题标题】:Success and failure function parameters Scala pattern成功和失败函数参数 Scala 模式
【发布时间】:2012-08-04 01:39:08
【问题描述】:

在 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 中的 Either,或者您可以使用 Future 调用并观察它是成功还是失败。
  • 两者都是真的糟糕的模式。

标签: scala closures anonymous-function function-parameter


【解决方案1】:

听起来你想要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"

但最好的部分是 Futures 是 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"

或者在理解中使用它们:

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多