In Kotlin, there is the apply
method:
inline fun <T> T.apply(block: T.() -> Unit): T (source)
Calls the specified function block with
this
value as its receiver and returnsthis
value.
This allows you to configure an object like the following:
val myObject = MyObject().apply {
someProperty = "this value"
myMethod()
}
myObject
would be the MyObject
after the apply {}
call.
Groovy has the with
method, which is similar:
public static <T,U> T with(U self, @DelegatesTo(value=DelegatesTo.Target.class,target="self",strategy=1) Closure<T> closure )
Allows the closure to be called for the object reference self.
...
And an example from the doc:
def b = new StringBuilder().with {
append('foo')
append('bar')
return it
}
assert b.toString() == 'foobar'
The part with the Groovy method is always having to use return it
to return the delegate of the with
call, which makes the code considerably more verbose.
Is there an equivalent to the Kotlin apply
in Groovy?
The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.
A built-in function is a function that is already available in a programming language, application, or another tool that can be accessed by end users. For example, most spreadsheet applications support a built-in SUM function that adds up all cells in a row or column.
The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract, or rearrange their members in place, and don't return a specific item, never return the collection instance itself but None .
The function is called tap
and is part of Groovy 2.5. See discussions about the naming in merge request.
Other than that, only foo.with{ bar=baz; it }
can be used. You can retrofit your own doto
, tap
, apply
, ... via metaprogramming.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With