T.apply(block...">

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 thisvalue as the receiver and returns the value this.

This allows you to configure the object as follows:

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

myObjectwill be myObjectafter the call apply {}.

Groovy has a method withthat 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 itto return the call delegate with, which makes the code much more verbose.

Is there a Kotlin equivalent applyin Groovy?

+4
source
1

tap Groovy 2.5. . .

, foo.with{ bar=baz; it }. doto, tap, apply,... .

+3

Source: https://habr.com/ru/post/1691473/


All Articles