The recently posted JEP 286, titled Local-Variable Type Inference, hints at the possible addition of
var identifier to the Java platform.
The inference could be done like this, for example :
var list = new ArrayList(); // infers ArrayList
var map = new HashMap(); // infers HashMap
In the proposal it is said that this would be restricted to local contexts like local variables with initializers, indexes in the enhanced for-loop, and locals declared in a traditional for-loop.
However, it should not be valid to have it as method signature, constructors, method return types, fields and many other forms.
A similar concept is already present in other languages including C# (var), Scala (var/val), Go (declaration with :=), Groovy (def), as well as quite a few others.
Is var final?
var keyword is not final and there are other syntax options to be considered like :
var x = expr only (like C#)
var, plus val for immutable locals (like Scala, Kotlin)
var, plus let for immutable locals (like Swift)
auto x = expr (like C++)
const x = expr (already a reserved word)
final x = expr (already a reserved word)
let x = expr
def x = expr (like Groovy)
x := expr (like Go)
How will it fit the current strucutre?
There are also many edge cases I can think of, and it will depend a good deal on how complex the realisation of this will be in practice.
Generics are one good example of the complexity and non-obvious issues that can arise in the realisation.
Whatever is picked as a keyword, there is a risk of someone having a variable with the same name, thus breaking backwards compatibility. If you ask me, if someone has a variable named as var or let, they might deserve to have their code break, but then again, Java has a reputation for keeping both source and bytecode compatibility in almost all of the cases.
There are also issues with the fantastic IDE support that Java developers are used to. How would they know the type in all of these cases? Most of these are already detailed in the proposal, but there are many open questions.
Overall, I believe it’s a step in the right direction, and it’s great to see that these topics are being publicly discussed, even it this never lands in Java. Moreover, given that the JEP features the names of Brian Goetz and Mark Reinhold, I’m fairly confident about its future.
What are your thoughts on this – aweseome or not ? Be sure to take the survey and let Oracle know.