Java 10 var: Difference between revisions
Line 7: | Line 7: | ||
The feature behind the Java 10 new keyword '''var''' is called local variable type inference. | The feature behind the Java 10 new keyword '''var''' is called local variable type inference. | ||
Local variable type inference is a new functionality added to the Java compiler, which is now able to infer the type of a variable from the [[Java_Language#Variable_Initializer|variable initializer]]. This new compiler functionality make possible to replace the type in a local variable declaration with the keyword <tt>var</tt>: | Local variable type inference is a new functionality added to the Java compiler, which is now able to infer the type of a variable from the [[Java_Language#Variable_Initializer|variable initializer]]. This new compiler functionality make possible to replace the type in a local variable declaration with the keyword <tt>var</tt>. The compiler fills in the appropriate type: | ||
Before <tt>var</tt>: | |||
<syntaxhighlight lang='java'> | |||
</syntaxhighlight> | |||
With <tt>var</tt>: | |||
<syntaxhighlight lang='java'> | <syntaxhighlight lang='java'> | ||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 16:30, 25 May 2018
Internal
Overview
The feature behind the Java 10 new keyword var is called local variable type inference.
Local variable type inference is a new functionality added to the Java compiler, which is now able to infer the type of a variable from the variable initializer. This new compiler functionality make possible to replace the type in a local variable declaration with the keyword var. The compiler fills in the appropriate type:
Before var:
With var:
Details
The var inference algorithm looks only at the expression being assigned to the variable in order to deduce the type.
var and Code Readability
Type inference reduces the amount of time it takes to write Java code, but in some cases does not necessarily improve its readability. Some say that developers spend much more time reading source coding than writing it, so probably the amount of time it takes to write the code should be optimized in favor of readability. This is an example where var does not improve readability:
var removes the reader ability to guess about the code's intent sim[ply from the type of the variable.
However, there may be cases when var actually improves readability by eliminating obviously redundant type declaration in a very local context. Logically, this is similar to naming a variable "i" instead of "internalProcessId" in a short loop. This is an example where var improves readability and it comes with an additional, not immediately obvious, advantage.