Skip to main content

New "for" syntax could respect "Closeable" interface.

2 replies [Last post]
soupdragon
Offline
Joined: 2006-01-07
Points: 0

It's a natural limitation of the new for() syntax that the Iterator (where applicable) can't be directly accessed. One of the situations where this is a problem is if an iterator uses resources, like a database cursor, for example that needs explicit closure when the loop is finished.

So how about the loop syntax checking if the Iterator implements Closeable and, if so, closing it when the loop exits? Ideally this should be done as if in a finally clause.

Or we could have a sub-interface of Iterable/Iterator which includes a close method signature.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
tackline
Offline
Joined: 2003-06-19
Points: 0

It would be far too easy to pass an iterator to code that does not respect Closeable. So, if this was to be done, I'd suggest parallel interfaces to Iterator and Iterable.

You might also want to consider where and what checked exceptions can be thrown. Perhaps something like:

interface ResourceIterable {
ResourceIterator resourceIterate() throws EXC;
}
interface ResourceIterator {
boolean hasNext() throws EXC;
T next() throws EXC;
void remove() throws EXC;
void close() throws EXC;
}

soupdragon
Offline
Joined: 2006-01-07
Points: 0

Be a bit weird, having checked exceptions thrown from invisible code.

Also how do you imagine [b]remove[/b] being called? That's another limitation of looping this way, incidentally.