-1

When I try to pass an array initializer as a method argument I get an error with the message 'Array initializer is not allowed here'.

methodTakingArrayArgument({0,0,0})

However, the construct works when the type is mentioned explicitly.

methodTakingArrayArgument(new int[]{0,0,0})

Is there a reason that this construct is not supported? There seems to be no documentation on the oracle website mentioning the same.

Edit: I understand that there are a fixed number of ways to create an array in Java. The array initializer construct felt natural to be supported as a first class citizen in Java, like in languages like typescript.

As one of the answers has pointed out, the array initializer is not a valid expression, which is why it cannot be passed on to a method.

Shivku
  • 156
  • 3
  • 10
  • 3
    I don't think there's a "reason" aside from Java not supporting this syntax. (Maybe there's a grammar or type ambiguity reason, but it seems unlikely that this would have been documented.) – nneonneo Feb 19 '20 at 04:17
  • Yeah, I'm really curious if there's a *reason*. Like people link the spec and stuff, OK, I get that this is how it works. But *why*? I don't think there's any particular reason that the compiler can get the type when the array is declared as a variable but it couldn't do the same for a method parameter - which also has to have a type. It's an interesting (and in my opinion, kinda user unfriendly) language design choice. Perhaps they want to enforce clarity, so that the actual type is always nearby when using this syntax? – rococo Nov 25 '21 at 02:11

1 Answers1

4

The Java Language Specification is the final authority on such questions: Chapter 15 Expressions in general, §15.12 Method Invocation Expressions and §15.10.1. Array Creation Expressions and 10.6. Array Initializers in particular. In a nutshell, what you'll discover is:

  1. The argument list of a method invocation consists of a series of comma-separated expression;
  2. new int[]{0,0,0} is an arrayCreationExpression, which, in turn, is a type of expression and thus allowable as an argument in a method invocation;
  3. {0,0,0} is an arrayInitializer which, by itself, is not an expression and thus not legal to use as an argument in a method invocation.
Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21