Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the name of the implicit variable in a java while loop?

In Perl you can write something like

while(!eof){  
    doSomething(x,y);  
    print $_;  
}

and the second statement prints out the iteration the loop is up to using $_, the name of the invisible variable Perl uses to iterate through the loop. What is the name of that variable in Java?

I realise that you can accomplish the same thing by declaring a variable outside the loop and incrementing it, but this way is definitely more elegant if anyone knows how to do it.

like image 605
Isaac Avatar asked Sep 18 '11 22:09

Isaac


2 Answers

There's no implicit variable in Java as in Perl. You just have to be more explicit in Java...

like image 139
Jordão Avatar answered Oct 04 '22 01:10

Jordão


There is no such concept in Java.

In Groovy, at least you get an it variable set on the functional methods.

myList = [1,2,3];
myList.each {
   println it
}

or to read a file, like in your example...

new File('test.txt').eachLine {
   println it
}
like image 22
Stefan Kendall Avatar answered Oct 04 '22 03:10

Stefan Kendall