官术网_书友最值得收藏!

Type inference with var

The following lines of code show how local variables (and all other variables) were defined prior to Java 10:

String name = "Java Everywhere"; 
LocalDateTime dateTime = new LocalDateTime.now();

Starting with Java 10, by using var, you can drop the mandatory explicit type in the declaration of local variables, as follows:

var name = "Java Everywhere";            // variable 'name' inferred as 
// String var dateTime = new LocalDateTime.now(); // var 'dateTime' inferred as
// LocalDateTime

Does it look like the preceding code doesn't offer a lot of benefits? Imagine you could take the following code:

HashMap<Integer, String> map = new HashMap<Integer, String>(); 

And replace it with this code, instead:

var map = new HashMap<Integer, String>();  

By replacing HashMap<Integer, String> with var, the preceding line of code is much shorter.

When you move away from explicitly stating the data type of the variables, the compiler takes over to determine, or infer, the variable type. Type inference is the compiler's ability to evaluate the information that is already present in the code, like the literal values, operations, and method invocations or their declarations, to determine the variable type. It follows a set of rules to infer the variable type. As a developer, when you choose type inference with var, you should be aware of the compiler's inference algorithm, so that you don't get unexpected results.

With every new feature, you should adhere to a few rules and restrictions and try to follow the best practices to benefit from that feature. Let's start with the compulsory initialization of the variables that are defined using var.

Type inference with var is not dynamic typing; Java is still a strong, static-typed language. The usage of var makes your code leaner; you can drop the type of the local variable from its definition.

主站蜘蛛池模板: 金阳县| 衡水市| 靖安县| 盐山县| 凭祥市| 博白县| 婺源县| 西乌珠穆沁旗| 任丘市| 江口县| 七台河市| 沛县| 新营市| 洪雅县| 遂昌县| 旬邑县| 桐庐县| 临桂县| 郁南县| 平谷区| 闽清县| 武功县| 呼玛县| 邵东县| 萨嘎县| 饶阳县| 涡阳县| 织金县| 宾阳县| 巩留县| 司法| 张北县| 凤阳县| 吴桥县| 涿鹿县| 三河市| 湾仔区| 玉溪市| 南川市| 湘乡市| 临武县|