why does comma(,) not cause to compilation error?

自闭症网瘾萝莉.ら 提交于 2019-12-19 05:08:53

问题


I am writing a code that and suddenly see that "," doesn't cause any compilation error. Why ?

What I mean

public enum A {
    B, C, ; // no compilation error
}

but

int a, b, ; // compilation error

回答1:


http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9

The Enumbody has the following specification:

{ [EnumConstantList] [,] [EnumBodyDeclarations] } 

As you can see there can be an optional comma after the EnumConstantList, this is just a notational convenience.




回答2:


The language was designed this way so that it's easy to add and reorder elements - particularly if each one is on a line on its own.

The comparison with declaring variables isn't a good one, but arrays allow for more values in the same way:

int[] foo = { 1, 2, 3, };

Basically, adding on extra values to a collection defined in source code is rather more common than wanting to add a variable to a declaration statement.




回答3:


The main advantages are that it makes multi-line lists easier to edit and that it reduces clutter in diffs.

Changing:

public enum Names{
     MANNY,
     MO,
     JACK,
}

to:

public enum Names{
     MANNY,
     MO,
     JACK,
     ROGER,
}

involves only a one-line change in the diff:

  public enum Names{ 
       MANNY,
       MO,
       JACK,
+      ROGER,
  }

This beats the more confusing multi-line diff when the trailing comma was omitted:

  public enum Names {
       MANNY,
       MO,
-      JACK
+      JACK,
+      ROGER
  }

The latter diff makes it harder to see that only one line was added and that the other line didn't change content.

Based on answer by Raymond : https://stackoverflow.com/a/11597911/5111897



来源:https://stackoverflow.com/questions/4699577/why-does-comma-not-cause-to-compilation-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!