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

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.

主站蜘蛛池模板: 新宁县| 云和县| 江口县| 盈江县| 彭山县| 武城县| 徐州市| 九台市| 新和县| 南安市| 姜堰市| 阿图什市| 牟定县| 新余市| 安西县| 潜江市| 淮南市| 石家庄市| 天祝| 定结县| 荥经县| 平远县| 南漳县| 房山区| 利川市| 保靖县| 新余市| 观塘区| 抚宁县| 南溪县| 汶川县| 辽阳县| 长顺县| 陈巴尔虎旗| 江陵县| 辽中县| 牙克石市| 新巴尔虎右旗| 凤阳县| 芜湖县| 金平|