问题描述
编辑
好的,这里的大反馈,让我指出了正确的方向。用于调用匿名闭包的用例是在Scalatra路由层中。我有一堆路由在不同类型下分组在一起,在这个例子中,团队请求是共同的:
Edit
ok, great feedback here, got me pointed in the right direction. Use case for invoking anonymous closure is in Scalatra routing layer. I have a bunch of routes that are grouped together under various types, in this example, requests common to teams:
class Router {
type TeamType <: _Controller with _Team
get("""(schedules|rosters|teamresults|teamstats)/\d{8}""".r) {
val clazz :: date = captures
val obj = (clazz match {
case "schedules" => new RosterController
case "rosters" => new ScheduleController
}).asInstanceOf[TeamType]
obj.show(date)
}
}
通过在aa自我调用的匿名闭包中包装match表达式,我们避免在每个匹配的情况下绑定FooController.asInstanceOf [TeamType],在返回的实例上,在进程中保持不变性(即不能val obj = clazz match {...}后跟类型转换为obj已经val'd)
By wrapping the match expression in a a self-invoked anonymous closure, we avoid tacking on "FooController.asInstanceOf[TeamType]" to each matched case, and instead do the type cast on returned instance, maintaining immutability in the process (i.e. could not "val obj = clazz match {...}" followed by type cast as obj has already been val'd)
我相信这是一种基于字符串类名创建对象实例时可以获得的简短形式。当然,说,可能有一个FP方法,做的工作有更大的简洁...
I believe that this is as short-form as one can get when creating object instances based on string class name. Of course, saying that, there is likely an FP approach that does the job with even greater concision...
无论如何很酷的东西,缺少匿名闭包从Groovy,现在我发现Scala已经覆盖了; - )
Anyway cool stuff, was missing anonymous closures from Groovy, and now I discover Scala has that covered as well ;-)
原始
不知道如何关闭Scala。在Groovy中,您可以定义和调用匿名闭包,如下所示:
Original
Not sure how to pull this off in Scala. In Groovy you can both define and invoke an anonymous closure like so:
{String s-> println(s) }("hello")
感谢
推荐答案
((s : String) => println(s))("hello")
对于返回类型,只需让Scala推断它。
As for the return type, just let Scala infer it.
scala> ((x : Int) => x < 4)(3)
res0: Boolean = true
这篇关于调用匿名闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!