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

Summary

In this chapter, we covered local variable inference, or var, as introduced in Java 10. The var type enables you to drop the explicit data type for a local variable in a method. We covered the various dos and don'ts for the usage of var. Limited to local variables, variables defined using var must be initialized with a value. They can be used with all types of variables—primitives and objects. Variables defined with var can also be passed to methods and returned from methods; method declaration compatibility rules apply.

To avoid risking your type safety with generics, ensure that you pass relevant information when using var with generics. Although it doesn't make a lot of sense, the use of explicit casting is allowed with variables defined using var.

We also covered ways in which type inference existed in previous versions of Java (5, 7, and 8). Toward the end, we covered why type inference is limited to local variables and is not allowed in the public API.

The use of meaningful variable names has always been recommended, and it is important. With var, it becomes even more important. Since var offers syntactic sugar, it doesn't make any sense to refactor your existing or legacy code to add the use of var.

主站蜘蛛池模板: 神池县| 石狮市| 安溪县| 德化县| 伊川县| 海南省| 曲麻莱县| 义乌市| 界首市| 灵山县| 双桥区| 蓬溪县| 高尔夫| 娱乐| 桓台县| 辽阳县| 峨山| 卓尼县| 黑水县| 永兴县| 寻乌县| 安平县| 拉萨市| 阆中市| 桦甸市| 旬邑县| 雷州市| 洪洞县| 鱼台县| 永城市| 呼和浩特市| 和顺县| 监利县| 延安市| 崇明县| 潼南县| 留坝县| 黔江区| 东兴市| 奉新县| 潜江市|