Wednesday, March 9, 2016

JEP 286: Java Will Get Local Variable Type Inference

The Proposal

A new JEP has been proposed by Brian Goetz that would simplify the writing of Java applications. The proposal is to introduce Local Variable Type Inference, a feature that exists in many other languages today. With this new proposed feature we could write code like:

var list = new ArrayList<String>();  // infers ArrayList<string>
var stream = list.stream();          // infers Stream<String>

According to the proposal, the local variable will be inferred to its most specific type. So, in the example above, the variable list will be of type ArrayList<String> and not just List<String> or Collection<String>. This makes sense and if we want to demote our objects, we simply have to declare them as we always did.

There is a debate over the meaning of var wether it should also mean that the variable should become automatically final. By analyzing a huge corpus of Java code, the team's main proposition now is that variables declared with var is, in fact, not final and if one wants it final, it could simply be declared as final var or there might be another syntax like val that effectively is the same thing as final var.

What Will Not Work?

Local type inference cannot be used for variables with no initializers or initializers with just null values. This is obvious since it is not possible to infer the value type from such statements. Examples of code that will not work is:

        var x;
  (cannot use 'val' on variable without initializer)

        var f = () -> { };
  (lambda expression needs an explicit target-type) 

        var g = null;
  (variable initializer is 'null')

        var c = l();
  (inferred type is non denotable)

        var m = this::l;
  (method reference needs an explicit target-type)

        var k = { 1 , 2 };
  (array initializer needs an explicit target-type) 


Local Type Inference would be restricted to local variables with initializers, indexes in the enhanced for-loop, and locals declared in a traditional for-loop. It would not be available for method formals, constructor formals, method return types, fields, catch formals, or any other kind of variable declaration.

A final note is that the word var is proposed to be a reserved type name and not a Java keyword. This means that code that uses var as a variable, method, or package name will not be affected; code that uses var as a class or interface name will be affected (but these names violate the Java naming conventions anyhow).

Read more on the JEP 286 here. You can also provide feedback to the JEP guys using a link on the JEP page.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.