Java try-with-resources syntax irregularity
So I was looking through some of the new features of java 7, including the try-with-resources bit.
I understand how it works and everything, I just noticed that the syntax used to specify the resources is a little odd.
try
(InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target))
{
// stuff
}
}
catch (Exception e) {
// stuff
}
Specifically the definition of resources:
try (InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target))
Is there any other place in java where separating statements开发者_Go百科 within a parenthesis block is valid?
The only other time I can think of is a for loop
for ( ; ; )
but that's not quite the same since there has to be exactly 2 ;
s, and statements are separated with a ,
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 statements are ;
delimited instead of ,
delimited? Is there even another comparable language that has a similar use of ;
separated statements inside of a ()
block? I can't think of an example in java, C, or python.
In general, statements are terminated with semicolons in Java. Note that try-with-resources differs from an assignment like int i = 1, j = 100;
because it doesn't require that each thing being initialized be of the same type. It's really just a series of assignment statements wrapped in parentheses.
That said, I don't think there really needs to be any precedent for using a certain syntax if it's easily understood.
Well, it doesn't have the semicolons, but Common Lisp has several constructs that follow this pattern. For example, to bind some values to variables in a limited scope (essentially what the "try with resources" is doing):
(let (x 5) (y 10) (z 100)
(...))
It has similar stuff for condition (exception) handling, and you can also write your own constructs as needed that would probably look the same. If you imagine the (x 5)
as int x = 5;
you can see the parallel.
精彩评论