We’ve seen several occasions throughout Java’s history where language designers added
“type inference” to help us write more concise code. Type inference is the idea that the
compiler can figure out the static types for you so you don’t have to type them. Until Java 9,
we had to mention the type of the local variable explicitly and ensure it was compatible with
the initializer used to initialize it. For example,
String say = "Hey!! Developers";
But from Java 10 introduce Local Variable Type Inference , we can also write as:
var say = "Hey!! Developers";
"var" is also used with primitives data types.
Where can’t you use local variable type inference?
(1) For starter, you cannot use it with fields and in method signatures. It’s only for local variables. E.g. the following is not possible:
public long process(var list) { }
(2) You cannot use local variable declarations without an explicit initialisation. This means,
you cannot just use the var syntax to declare a variable without a value. You cannot
initialize a var variable to null either. The following:
var x; // error : cannot use without intializer
var emptyList = null; // error : cannot initializer as "null"
(3) You cannot also use var with lambda expressions because they require an explicit
target-type.
var p = (String s) -> s.length() > 10; // error: lambda expression needs an explicit target-type
(4) Same is the case with the array initializer:
var arr = { 1, 2, 3 }; // error: array initializer needs an explicit target-type
Type inference definitely reduces the amount of time taken to write Java code but what
about readability? Developers spend about 10x as much time reading source code as they
do writing it, so you should definitely be optimising for ease of reading over ease of writing.
The extent to which var improves this will always be subjective, it’s inevitable that some
people will hate var and some love it. You should always be focussing on what helps your
team-mates read your code so if they are happy reading code with var in then you should
use it, otherwise not.
Comments