在本文中,我们将看到作为JEP 286的一部分提出的名为Local Variable Type Inference的Java10功能。 从Java的第一个版本开始,它是一种强类型语言,在这里我们需要提及每种变量数据类型。 我们所有人都感到Java是冗长的语言,并期望精确,紧凑的Java编写方式。 Java 8解决了这个问题。
Java 10在初始化程序中添加了局部变量类型推断 ,以消除冗长的内容。 例如,
jshell> Map<String,String> map = new HashMap<>();
jshell> var map = new HashMap<>(); //This is valid with Java10
这里的LHS变量数据类型将由RHS语句确定。 例如,
jshell> var i = 3;
i ==> 3 //based on RHS, the LHS datatype is int.
jshell>int i=3,j=4; //Valid Declaration
but,
jshell> var j=4,k=5; //Not a Valid Declaration
| Error:
|'var' is not allowed in a compound declaration
| var j=4,k=5;
|^
您可以将此功能用于增强的for循环和for循环。
jshell> List names = Arrays.asList("ABC","123","XYZ");
names ==> [ABC, 123, XYZ]
jshell> for(var name : names){
...> System.out.println("Name = "+ name);
...> }Name = ABC
Name = 123
Name = XYZ
我们也可以在for循环中使用局部变量类型推断。
jshell> int[] arr = {1,2,3,4};
arr ==> int[4] { 1, 2, 3, 4 }jshell> for (var i=0;i<arr.length;i++){...> System.out.println("Value = "+i);...> }
Value = 0
Value = 1
Value = 2
Value = 3
在某些情况下,此功能无效。 例如,
- 对构造函数变量无效
- 对实例变量无效
- 对方法参数无效
- 无效以分配NULL值
- 无效作为返回类型
让我们看看上述声明的示例。
jshell> public class Sample {...> private var name = "xyz";...> public Sample(var name) {...> this.name=name;...> }...> public void printName(var name){...> System.out.println(name);...> }...> public var add(int a, int b) {...> return a+b;...> }...> }
| Error:
| 'var' is not allowed here
| private var name = "xyz"; //Instance variable
| ^-^
| Error:
| 'var' is not allowed here
| public Sample(var name) { //Constructor variable
| ^-^
| Error:
| 'var' is not allowed here
| public void printName(var name){ //Method parameter
| ^-^
| Error:
| 'var' is not allowed here
| public var add(int a, int b) { //Method return type
| ^-^
jshell> public class Sample {...> ...> public static void main(String[] args) {...> var s = null;...> }...> }
| Error:
| cannot infer type for local variable s
| (variable initializer is 'null')
| var s = null;
| ^-----------^
当我们从较低版本迁移到Java10时,我们不必担心本地变量类型推断,因为它具有向后兼容性。
在接下来的文章中,我们将学习另一个主题。 直到敬请期待!
翻译自: https://www.javacodegeeks.com/2018/06/local-variable-type-inference.html