我想标题本身就说明了问题——Groovy有类似Kotlin的作用域函数吗?
obj.apply {
foo()
bar()
baz()
}
// is the same as
obj.foo()
obj.bar()
obj.baz()
Groovy的obj.with { }
方法允许您做同样的事情:
obj.with {
foo()
bar()
baz()
}
也有obj.tap { }
变体(相当于obj.with(true) { }
)做同样的事情,但它返回传入的对象。
def newObj = obj.tap {
foo()
bar()
baz()
}
<一口>来源:http://docs.groovy-lang.org/docs/next/html/documentation/style-guide.html _using_with_and_tap_for_repeated_operations_on_the_same_bean 一口>