On 01/16/2015 06:46 PM, Ivan Gerasimov wrote:

Might it also make sense to allow anonymous variables in the try-with-resource statement? So that something like `try (() -> System.out.println("closed")) {}` would work...

I don't think that is necessary. In JDK 7, we started out allowing a general AutoCloseable expression in a try-with-resources statement and that proved problematic. Supporting a final / effectively final variable seems to be the right balance. The rationale is written up in the JSR 334 materials.


Yes, I agree. And it can easily be moved to the finally block, of course.
However, this:

        ExecutorService executor = ...;
        try (executor::shutdown) {
        }

still looks a bit more attractive to me, comparing to `try (Closeable c = executor::shutdown) {`
Maybe one day ... :-)

Sincerely yours,
Ivan


If try-with resources was designed after lambdas, various other forms could be considered. For example, the following:

try (SomeType var = expression; expression with (target) type Consumer<? super SomeType>) {
...
}


The example with ExecutorService would then read:

try (ExecutorService executor = Executors.newCachedThreadPool(); ExecutorService::shutdown) {
    ... use executor ...
}

This could even be done in the future as the 2nd form of try-with-resources. Maybe one day ... :-)


Peter

Reply via email to