Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Groovy 'it'?

Tags:

groovy

I have a collection which I process with removeIf {} in Groovy. Inside the block, I have access to some it identifier. What is this and where is it documented?

like image 991
TMOTTM Avatar asked Feb 27 '19 09:02

TMOTTM


People also ask

What is Groovy and why it is used?

Groovy is a scripting language with Java-like syntax for the Java platform. The Groovy scripting language simplifies the authoring of code by employing dot-separated notation, yet still supporting syntax to manipulate collections, Strings, and JavaBeans.

What is Groovy technology?

Groovy is a dynamic object-oriented programming language for the Java virtual machine (JVM) that can be used anywhere Java is used. The language can be used to combine Java modules, extend existing Java applications and write new applications.

What is it variable in Groovy?

Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.

What is :? In Groovy?

The operator returns the value on the left if the value on the left evaluates to "true" per Groovy truth rules.


Video Answer


2 Answers

it is an implicit variable that is provided in closures. It's available when the closure doesn't have an explicitly declared parameter.

When the closure is used with collection methods, such as removeIf, it will point to the current iteration item.

It's like you declared this:

List<Integer> integers = [1, 2, 3]
for(Integer it: integers) {print(it)}

When you use each, instead (and that's an example), you can get it implicitly provided:

integers.each{print(it)} //it is given by default

Or

integers.removeIf{it % 2 == 0} //it is the argument to Predicate.test()

it will successively take the values 1, 2, and 3 as iterations go.

You can, of course, rename the variable by declaring the parameter in the closure:

integers.each{myInteger -> print(myInteger)}

In this case, Groovy doesn't supply the implicit it variable. The documentation has more details

like image 93
ernest_k Avatar answered Sep 18 '22 22:09

ernest_k


If you create a closure without an explicit argument list, it defaults to having a single argument named it. Here's an example that can be run in the Groovy console

Closure incrementBy4 = { it + 4 }

// test it
assert incrementBy4(6) == 10

In the example above the closure is identical to

Closure incrementBy4 = { it -> it + 4 }

Here's another example that uses removeIf

Closure remove2 = { it == 2 }

def numbers = [1, 2, 3]
numbers.removeIf(remove2)

// verify that it worked as expected
assert numbers == [1, 2] 
like image 33
Dónal Avatar answered Sep 18 '22 22:09

Dónal