A built-in method of type "c" that returns the object on which it was called
There is a method in Kotlin apply
:
inline fun <T> T.apply(block: T.() -> Unit): T (source)
Calls the specified block function with the
this
value as the receiver and returns the valuethis
.
This allows you to configure the object as follows:
val myObject = MyObject().apply {
someProperty = "this value"
myMethod()
}
myObject
will be myObject
after the call apply {}
.
Groovy has a method with
that is similar:
public static <T,U> T with(U self, @DelegatesTo(value=DelegatesTo.Target.class,target="self",strategy=1) Closure<T> closure )
Allows to cause closure for the reference to the self object.
...
And an example from the document:
def b = new StringBuilder().with {
append('foo')
append('bar')
return it
}
assert b.toString() == 'foobar'
The Groovy method part should always be used return it
to return the call delegate with
, which makes the code much more verbose.
Is there a Kotlin equivalent apply
in Groovy?