内置“with”types方法,返回被调用的对象

在Kotlin中,有一个apply方法 :

 inline fun  T.apply(block: T.() -> Unit): T (source) 

使用this值作为接收方调用指定的function块并返回this值。

这使您可以像下面这样配置一个对象:

 val myObject = MyObject().apply { someProperty = "this value" myMethod() } 

apply {}调用之后, myObject将是MyObject

Groovy有with类似的方法 :

 public static  T with(U self, @DelegatesTo(value=DelegatesTo.Target.class,target="self",strategy=1) Closure closure ) 

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

还有一个来自doc的例子:

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

带有Groovy方法的部分总是不得不使用return it来返回with调用的委托,这使得代码更加冗长。

在Groovy中是否有相当于Kotlin的apply

该function被称为tap ,是Groovy 2.5的一部分。 查看关于合并请求中的命名的讨论。

除此之外,只有foo.with{ bar=baz; it } foo.with{ bar=baz; it }可以使用。 你可以改装你自己的dototapapply ,…通过元编程。

Interesting Posts