Groovy中int和Integer类型之间的区别

Abh*_*ute 5 groovy types groovyshell type-conversion

我刚刚开始学习groovy,正在阅读“ Groovy in Action”。在这本书中,我遇到了一条声明,即声明变量还是强制类型为int或Integer都无关紧要.Groovy都使用引用类型(Integer)。

所以我试图为类型为int的变量赋

int a = null
Run Code Online (Sandbox Code Playgroud)

但这给了我例外

org.codehaus.groovy.runtime.typehandling.GroovyCastException:无法将类为“ null”的对象“ null”转换为类“ int”。在Script1.run(Script1.groovy:2)上尝试使用“ java.lang.Integer”

然后我尝试将值分配给Integer类型的变量

Integer a = null
Run Code Online (Sandbox Code Playgroud)

而且工作正常。

谁能帮助我了解groovy这种行为方式或背后的原因?

小智 5

当您调用基元时,Groovy 始终使用包装类型

int a = 100
assert Integer == a.class
Run Code Online (Sandbox Code Playgroud)

groovy 在使用 int 值之前将其包装为 Integer 但 groovy 不能将 int 值设置为 null,因为变量是 int(原始类型)而不是 Integer。

int a = 100
int b = 200
a + b not int + int, but Integer + Integer
Run Code Online (Sandbox Code Playgroud)


Sau*_*aur 5

核心问题是原语不能为 null。Groovy 通过自动装箱来伪造它。

如果将null值存储在数字中,则不能将其存储在int/long/etc字段中。将 a 转换null number为 0是不正确的,因为这可能是有效值。Null意味着尚未做出任何价值或选择。

int是 aprimitive type并且它不被视为object。只有objects可以有一个null值,而int值不能null因为它是值类型,而不是引用类型

对于primitive types,我们有固定的内存大小,即因为int我们有4 bytes并且null仅用于objects因为内存大小不固定。

所以默认情况下我们可以使用:-

int a = 0
Run Code Online (Sandbox Code Playgroud)