views:

99

answers:

3

I am new to Eclipse which I use primarily for Java. I have previously used IntelliJ Idea in which it is possible to select a variable which extends Iteratable (Collection, List etc) and have it produce a correct foreach loop.

I know Eclipse does something similar with the foreach template, where it guesses which variable to iterate over, but I can't get it to the same thing with a selected variable. But what if the variable is not in the current scope and what if Eclipse guesses wrong?

So what I am trying to do is being able to select a variable (or function which returns a variable) which implements Iterator and have it return:

Selection:

functionWhichReturnsList()   (which returns List<TypeOfItemsInList>)

Result:

for (TypeOfItemsInList item : functionWhichReturnsList()) {  
   ${cursor}  
}

Any ideas?

A: 

As far as I know Eclipse does not support that in the way you describe.

If Eclipse does not find the right variable you can use the tabulator key to iterate through the placeholders in the foreach template. At the iterable point eclipse will show you a list of iterables you can choose from.

A: 

You probably cannot do that in eclipse, but type for and hit Ctrl-Space twice you will see the code templates menu pop up. Then you could select functionWhichReturnsList() in proper place and eclipse will do the rest.

fastcodejava
+1  A: 

I typically create code like this by following these steps:

Call the function and use Ctrl-1 to create a local variable holding the return value:

List<TypeOfItemsInList> list = functionWhichReturnsList()

Type fore[Ctrl-space] to insert the for loop (since eclipse usually chooses the closest iterable when constructing the loop):

List<TypeOfItemsInList> list = functionWhichReturnsList()

for (TypeOfItemsInList item : list) {
}

Inline the local variable by putting the cursor on the list variable and typing Alt-Ctrl-i:

for (TypeOfItemsInList item : functionWhichReturnsList()) {
}

It's not optimal, but it works.

ChrisH
This is the method I have been using as well, but it is annoying to say the least.Perhaps this is plugin territory? Or perhaps a change in the template system in Eclipse itself?
Casper