Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built-in 'with' type method that returns the object it was called on

Tags:

groovy

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 returns this 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?

like image 602
mkobit Avatar asked Dec 28 '17 19:12

mkobit


People also ask

What is the name of the built in function to return the type of an object?

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.

What is a built in method?

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.

What are built in object types in Python?

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 .


1 Answers

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.

like image 169
cfrick Avatar answered Oct 16 '22 08:10

cfrick