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

前端 未结 2 998
北荒
北荒 2021-01-06 06:37

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 =          


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-06 06:50

    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.

提交回复
热议问题