Thursday 17 December 2015

Trailing Commas

This post might seem trivial, but I decided to go ahead with it.

I recently found out that the following code compiles.
/**
 * The Seasons.
 * @author mr.bear
 */

public enum Seasons
{
    SPRING, SUMMER, AUTUMN, WINTER,
}
I was a little surprised, that the last comma was not a problem. The same can be seen in the following array initializer:
int[] b = {1, 2, 3, 4, 5, 6,};

Apparently, to my surprise, it's written in the JLS.

According to [1], if you look at the Grammar defined for Enums:
EnumBody:
{ [EnumConstantList] [,] [EnumBodyDeclarations] }
For arrays the same rule applies2.
“A trailing comma may appear after the last expression in an array initializer and is ignored.”
I was a little surprised that it has been part of the spec for a very long time3.

References

[1] JLS 8.0 Section 8.9.1 Enum Constants
https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.1
[2] JLS 8.0 Section 10.6
https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.6
[3] JSL 1.0
http://titanium.cs.berkeley.edu/doc/java-langspec-1.0/
StackOverflow - Arrays with trailing commas inside an array initializer in java
http://stackoverflow.com/questions/11621917/arrays-with-trailing-commas-inside-an-array-initializer-in-java

No comments:

Post a Comment