Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are compound definitions using 'var' not allowed?

Tags:

java

java-10

Well, I really thought that this would work (inside a method):

var x, y = 1;

var x = 1, y = 2;

But it does not, it would not compile - "var is not allowed in a compound definition".

I guess the reason for this is an usual trade-off. This is not a very used feature and thus not implemented, but we could yes and may be might in a future release...

like image 817
Eugene Avatar asked Mar 07 '18 14:03

Eugene


1 Answers

Well, if you give it a manifest type:

int x, y = 1;

This declares two int variables, and initializes one of them. But local variable type inference requires an initializer to infer a type. So you're dead out of the gate.

But, suppose you meant to provide an initializer for both. It's "obvious" what to do when both initializers have the same type. So let's make it harder. Suppose you said:

var x = 1, y = 2.0;

What is this supposed to mean? Does this declare x as int and y as float? Or does it try to find some type that can be the type of both x and y? Whichever we decided, some people would think it should work the other way, and it would be fundamentally confusing.

And, for what benefit? The incremental syntactic cost of saying what you mean is trivial compared to the potential semantic confusion. And that's why we excluded this from the scope of type inference for locals.

You might say, then, "well, only make it work if they are the same type." We could do that, but now the boundary of when you can use inference and when not is even more complicated. And I'd be answering the same sort of "why don't you" question right now anyway ... The reality is that inference schemes always have limits; what you get to pick is the boundary. Better to pick clean, clear limits ("can use it in these contexts") than fuzzy ones.

like image 74
Brian Goetz Avatar answered Nov 16 '22 05:11

Brian Goetz