加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – “闭包”如何使用它实现对象系统和基本控制结构这样一

发布时间:2020-12-16 18:02:33 所属栏目:安全 来源:网络整理
导读:以下是 programming scala第1章的引用: Closures are such a powerful abstraction that object systems and fundamental control structures are often implemented using them 显然,该声明并非专门针对Scala,而是关于闭包,但我不能 从中学到很多东西.也许
以下是 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 parameters
  • unless(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"

合理?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读