groovy 中 int 和 Integer 类型的区别

difference between int and Integer type in groovy

我刚开始学习groovy,正在阅读"Groovy in Action"。 在这本书中,我遇到了一个声明,即 无论您是将变量声明或强制转换为 int 类型还是 Integer.Groovy 使用引用类型 ( Integer ) 都没有关系。

所以我尝试将 null 值分配给类型为 int

的变量
int a = null

但它给了我以下异常

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'null' with class 'null' to class 'int'. Try 'java.lang.Integer' instead at Script1.run(Script1.groovy:2)

然后我尝试将 null 值分配给类型为 Integer

的变量
Integer a = null

它工作得很好。

任何人都可以帮助我了解 groovy 的行为方式或背后的原因吗?

据我了解,如果您使用文字,Groovy 会使用包装器类型。例如:

def a = 11 // equivalent to Object a = 11. 11 is an java.lang.Integer

assert ['java.lang.Integer'] == [ 11, 22, 33 ]*.class*.name.unique()

虽然如果您在定义中使用特定类型,编译器必须执行转换。

你可以这样做:

def a = 11
a = 'ssss'

但是

int a = 11 // or int a
a = 'ssss'

给出 GroovyCastException.

这是你在你的案例中看到的

Groovy 在您 调用 原语时始终使用包装器类型

int a = 100
assert Integer == a.class

groovy 接受 int 并将其包装成 Integer,然后再使用它的值 但是groovy不能将int值设置为null,因为变量是int(原始类型)而不是Integer。

int a = 100
int b = 200
a + b not int + int, but Integer + Integer

核心问题是primitives can’t be null. Groovy fakes that out with autoboxing

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

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

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

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

int a = 0