有人可以在文档中解释Groovy命令链dsl示例...文本已解析为映射和闭包

问题描述

show = { println it }
square_root = { Math.sqrt(it) }

def please(action) {
  [the: { what ->
    [of: { n -> action(what(n)) }]
  }]
}

// equivalent to: please(show).the(square_root).of(100)

please show the square_root of 100
// ==> 10.0

我知道请(显示)返回一个对象,该对象具有一个称为[param]的方法,而该方法又返回一个具有[param]方法的对象。

我不明白的是,“请显示100的平方根”这一行是如何在请(显示)之后转换为地图和闭包的。

解决方法

这里的关键是写出代码而无需“可选”调用, 成员访问权限丢失。那是:

please(show).the(square_root).of(100)

此方法的工作方式是,通过返回一个地图,用(在 至少)“在句子中”的键,该键再次具有闭包作为 继续这个链条。

因此,将其写得更加冗长(例如 链中的链接):

.getAt('the').call(square_root)