Generic return type is not inferred in for-each loop
Hello,
I've come across this situation where I need to use a method with generic return type inside a for-each (enhanced for) loop.
The generic method is this:
Code:
/** Returns an Iterable for a IDfList */
public static <E> Iterable<E> getIterable(IDfList list) {
return new IterableIDfList<E>(list);
}
Then, I can use it this way:
Code:
Iterable<IDfCopyNode> copyNodes = DfcUtil.getIterable(copyOp.getNodes()); // Infers the return type
for ( IDfCopyNode node : copyNodes ) ...
But I can't inline the copyNodes variable:
Code:
for ( IDfCopyNode node : DfcUtil.getIterable(copyOp.getNodes()) ) ... // WON'T COMPILE; doens't infer type
To do it, I must explicitly put the generic type:
Code:
for ( IDfCopyNode node : DfcUtil.<IDfCopyNode>getIterable(copyOp.getNodes()) ) ...
Do you know why? Shouldn't the compiler infer the generic type in the for-each like in the simple assignation? After all, I suppose the for-each loop performs a simple assignation behind the scenes.
Thank you!
Fran