内置'with'类型方法,返回调用它的对象

mko*_*bit 5 groovy

在Kotlin,有一种apply方法:

inline fun <T> T.apply(block: T.() -> Unit): T (source)
Run Code Online (Sandbox Code Playgroud)

调用指定的功能,将this值作为其接收器并返回this值.

这允许您配置如下对象:

val myObject = MyObject().apply {
  someProperty = "this value"
  myMethod()
}
Run Code Online (Sandbox Code Playgroud)

myObject将是MyObjectapply {}电话会议之后.

Groovy有这样的with方法,类似于:

public static <T,U> T with(U self, 
  @DelegatesTo(value=DelegatesTo.Target.class,target="self",strategy=1)
  Closure<T> closure
)
Run Code Online (Sandbox Code Playgroud)

允许为对象引用self调用闭包.

...

以及来自doc的一个例子:

def b = new StringBuilder().with {
  append('foo')
  append('bar')
  return it
}
assert b.toString() == 'foobar'
Run Code Online (Sandbox Code Playgroud)

使用Groovy方法的部分总是必须用来return it返回with调用的委托,这使代码更加冗长.

是否有相当于applyGroovy中的Kotlin ?

cfr*_*ick 6

该函数被调用tap并且是 Groovy 2.5 的一部分。请参阅合并请求中有关命名的讨论。

除此之外,只能foo.with{ bar=baz; it }使用。您可以通过元编程改造您自己的doto、、、...。tapapply