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
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:
{ [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.


[1] JLS 8.0 Section 8.9.1 Enum Constants
[2] JLS 8.0 Section 10.6
[3] JSL 1.0
StackOverflow - Arrays with trailing commas inside an array initializer in java

No comments:

Post a Comment