Enhance the Java Language to extend type inference to declarations of local variables with initializers大体意思就是用于带有初始化的局部变量声明,废话不多说,我们直接用具体代码来展示实际的作用。
The majority (more than 75% in both JDK and broader corpus) of local variables with initializers were already effectively immutable anyway, meaning that any "nudge" away from mutability that this feature could have provided would have been limited.超过75%的JDK库及其相关扩展中,带有初始化的局部变量,都是有效不可变的,即使提供了延后初始化功能起到的作用也不大。
We chose the restriction ... because it covers a significant fraction of the candidates while maintaining the simplicity of the feature and reducing "action at a distance" errors.使用这种方式既能覆盖绝大数使用场景,又能保持功能简洁,另外一方面也是为了减少可能存在的维护问题,理解的心智成本,例如声明后经过几百行的代码再进行初始化。
java: 无法推断本地变量 listAfter10 的类型如果使用IDE,都不用运行就会直接提示你,例如Intellij IDEA:
(无法在不带初始化程序的变量上使用 'var')
Cannot infer type:'var' on variable without initializer回看之前说到的官方声明,“type inference to declarations of local variables with initializers”,with initializers已经很好说明使用它必须初始化,否则编译器无法进行类型推断。
Cannot infer type:variable initializer is 'null'3. 不能用于非局部变量
此处不允许使用 'var'4. 不能用于Lambda表达式类型的声明
Cannot infer type:lambda expression requires an explicit target type编译直接报错
java: 无法推断本地变量 lambdaVar 的类型但是这样使用是可以的:
(lambda 表达式需要显式目标类型)
In theory, it would be possible to have a lambda expression like the last line above, which is semi-explicitly typed (or semi-implicitly typed, depending on your point of view). However, it is outside the scope of this JEP because it deeply affects type inference and overload resolution.This is the main reason for keeping the restriction that a lambda expression must specify all manifest parameter types or none.使用规范
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) | Powered by Discuz! X3.4 |