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

前端 未结 2 980
北荒
北荒 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 07:04

    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);
    

提交回复
热议问题