Can a local variable with an inferred type be reassigned to a different type?

好久不见. 提交于 2019-12-03 21:05:50

问题


I remember reading somewhere that local variables with inferred types can be reassigned with values of the same type, which would make sense.

var x = 5;
x = 1; // Should compile, no?

However, I'm curious what would happen if you were to reassign x to an object of a different type. Would something like this still compile?

var x = 5;
x = new Scanner(System.in); // What happens?

I'm currently not able to install an early release of JDK 10, and did not want to wait until tomorrow to find out.


回答1:


Would not compile, throws "incompatible types: Scanner cannot be converted to int". Local variable type inference does not change the static-typed nature of Java. In other words:

var x = 5;
x = new Scanner(System.in);

is just syntactic sugar for:

int x = 5;
x = new Scanner(System.in);



回答2:


Once a var variable has been initialized, you cannot reassign it to a different type as the type has already been inferred.

so, for example this:

var x = 5;
x = 1; 

would compile as x is inferred to be int and reassigning the value 1 to it is also fine as they're the same type.

on the other hand, something like:

var x = 5;
x = "1"; 

will not compile as x is inferred to be int hence assigning a string to x would cause a compilation error.

the same applies to the Scanner example you've shown, it will fail to compile.



来源:https://stackoverflow.com/questions/49372970/can-a-local-variable-with-an-inferred-type-be-reassigned-to-a-different-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!