Is there any way to remove variable "i" in the following example and still get access to index of item that being printed ?
def i = 0;
"one two three".split().each {
println ("item [ ${i++} ] = ${it}");
}
=============== EDIT ================
I found that one possible solution is to use "eachWithIndex" method:
"one two three".split().eachWithIndex {it, i
println ("item [ ${i} ] = ${it}");
}
Please do let me know if there are other solutions.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.
You can print the current value of a variable with the println function.
you can use eachWithIndex()
"one two three four".split().eachWithIndex() { entry, index ->
println "${index} : ${entry}" }
this will result in
0 : one
1 : two
2 : three
3 : four
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