Incorrect Java syntax try-with-resources

So, I was looking at some new features of java 7, including try-with-resources .

I understand how this works and that's it, I just noticed that the syntax used to specify resources is a bit strange.

try (InputStream fis = new FileInputStream(source); OutputStream fos = new FileOutputStream(target)) { // stuff } } catch (Exception e) { // stuff } 

In particular, the definition of resources:

 try (InputStream fis = new FileInputStream(source); OutputStream fos = new FileOutputStream(target)) 

Is there another place in java where the separation of statements inside a block of brackets really is?

The only time I can think of is a loop cycle

 for ( ; ; ) 

but this is not quite the same, since there must be exactly 2 ; s, and the operators are separated using, as in

 for (int i = 1, j = 100; i <= 100, j > 0; i = i-1, j = j-1) 

So my question is: where did this syntax come from? Is there a reason the expressions are ; limited, not limited? Is there another comparable language that has a similar use ; separated statements inside a block () ? I can't come up with an example in java, C or python.

+7
source share
2 answers

In general, statements end with a semicolon in Java. Note that try-with-resources is different from an assignment of type int i = 1, j = 100; , because it does not require that each initialized thing be of the same type. This is really just a series of assignment operators enclosed in parentheses.

However, I do not think that any precedent is really necessary for using a specific syntax, if it is easily understood.

+7
source

Well, it has no semicolons, but Common Lisp has several constructs that follow this pattern. For example, bind some values ​​to variables in a limited area (essentially what try with resources does):

 (let (x 5) (y 10) (z 100) (...)) 

It has similar material for handling conditions (exceptions), and you can also write your own constructions as needed, which are likely to look the same. If you represent (x 5) as int x = 5; , you can see the parallel.

0
source

All Articles