以下是
programming scala第1章的引用:
Closures are such a powerful abstraction that object systems and fundamental control structures are often implemented using them
显然,该声明并非专门针对Scala,而是关于闭包,但我不能
从中学到很多东西.也许它是一些智慧的珍珠,仅适用于那些强大的编译器作者!
那么谁使用Closures实现基本控制结构?为什么?
编辑:我记得在groovy中使用闭包作为方法调用的最后一个参数的语法阅读有关自定义控件结构的内容,并使用元类或使用Categories的关键字使结构可用于您的代码.这可能是相关的吗?
编辑:我找到了groovy自定义控件结构语法here的以下参考(幻灯片38):
Custom control structures
Thanks to closures
- When closures are last,they can be put “out” of the parentheses
surrounding parametersunless(account.balance > 100.euros,{ account.debit 100.euros })
unless(account.balance > 100.euros) { account.debit 100.euros }
- Signature
def unless(boolean b,Closure c)
显然,groovy提供的是一种语法糖,用于使基于Closure的自定义控制结构看起来像语言本身提供的一流控制结构.
解决方法
我评论了控制结构的情况.让我评论闭包作为对象.考虑在对象上调用方法时会发生什么;它不仅可以访问参数列表,还可以访问对象的字段.也就是说,方法/函数关闭字段.这与关闭范围中的变量的“裸”函数(即,不是对象方法)没有什么不同.但是,对象语法提供了一个很好的抽象和模块化机制.
例如,我可以写
case class Welcome(message: String) { def greet(name: String) = println(message + "," + name) } val w = Welcome("Hello") w.greet("Dean")
与
val message = "Hello" val greet = (name: String) => println(message + "," + name) greet("Dean")
实际上,在这个例子中,我可以从Welcome中删除“case”关键字,因此该消息不会成为字段,但值仍在范围内:
class Welcome2(message: String) { // removed "case" def greet(name: String) = println(message + "," + name) } val w = new Welcome2("Hello") // added "new" w.greet("Dean")
它仍然有效!现在greet关闭输入参数的值,而不是字段.
var welcome = "Hello" val w2 = new Welcome2(welcome) w2.greet("Dean") // => "Hello,Dean" welcome = "Guten tag" w2.greet("Dean") // => "Hello,Dean" (even though "welcome" changed)
但是如果类直接引用外部作用域中的变量,
class Welcome3 { // removed "message" def greet(name: String) = println(welcome + "," + name) // reference "welcome" } val w3 = new Welcome3 w3.greet("Dean") // => "Guten tag,Dean" welcome = "Buon giorno" w3.greet("Dean") // => "Buon giorno,Dean"
合理?