可以将具有推断类型的局部变量重新分配给其他类型吗? [英] Can a local variable with an inferred type be reassigned to a different type?

查看:121
本文介绍了可以将具有推断类型的局部变量重新分配给其他类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得在某地读过带有推断类型的局部变量可以用相同类型的值重新分配,这是有道理的。

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?

然而,我很好奇如果你要重新分配 x会发生什么到不同类型的对象。这样的东西还能编译吗?

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?

我目前无法安装JDK 10的早期版本,也不想等待直到明天才发现。

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

推荐答案

不会编译,抛出不兼容的类型:扫描程序无法转换为int 。局部变量类型推断不会改变Java的静态类型性质。换句话说:

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

只是语法糖:

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

这篇关于可以将具有推断类型的局部变量重新分配给其他类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆