Trailing ","? No Problem!


Blogs: Trailing ","? No Problem!

  1. Trailing ","? No Problem! (2 messages)

    Dushan Hanuska was generating code when he made the mistake of adding a trailing comma to the final element in an array initialization. Only the mistake turned out not to be a mistake. Here is the code List initList = Arrays.asList(new Integer[] { new Integer(1), new Integer(2), new Integer(1), new Integer(2), }); Dushan was quite surprised to see that his IDE didn't complain. He was even more surprised to find that the code not only compiled but ran perfectly ok. His curiosity lead him to the Java Language Specification where in section 10.6 he discovered that "A trailing comma may appear after the last expression in an array initializer and is ignored". Mystery solved. The interesting about sharing discoveries such as this is sometimes you can learn even more from people who leave comments. In this instance you may be surprised to learn that this is also a feature in JavaScript. As you could imagine, this helps normalize code generation code.

    Threaded Messages (2)

  2. Traling "," in JavaScript[ Go to top ]

    In this instance you may be surprised to learn that this is also a feature in JavaScript.
    But be aware: A snippet like this:{ url : '', handler: replaceFilterSelection, mimetype: "text/html", content: {attribute: "test"}, }); (see the trailing comma after content) will work in Firefox, but lead IE to errors... Greetings, Michael.
  3. Useful in Enums[ Go to top ]

    I found this to be useful in an Enum I was recently making: enum ModifierElement { ... MOD_PUBLIC("public"), MOD_PROTECTED("protected"), MOD_PRIVATE("private"), MOD_DEFAULT("default")/*special default-access specifier*/, ; ... } I wanted my comment to be seen as unmistakably about the MOD_DEFAULT member. Had I not added the comma I could have ended up adding or changing the list later on, being just one autoformat away from it looking like I was commenting on the next element instead. Using the trailing comma is similar to always using braces: it can look cluttered, but it makes copying and pasting lines of code (and other modifications) much easier.