2012-08-07 62 views
2

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

这个约定与node.js库通常所做的相似,但我只是想知道是否有另一种方法可以在Scala中执行此操作。

例如:

def performAsyncAction(n: BigInt, 
       success: (BigInt) => Unit, 
       failure: FunctionTypes.Failure): Unit = { 

然后到函数调用

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

感谢

+0

您可以使用在未来的封装本或者你可以使用一个未来的呼叫,看它是否成功或失败。 – 2012-08-07 06:19:40

+0

要么是**真的**不好的模式。 – 2012-08-07 09:16:13

+2

为什么要么是坏模式? – Hakkar 2012-08-07 17:10:19

回答

8

这听起来像你想有一个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 s为单子,这样你就可以创建异步管道使用的东西的动作像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"