Reputation: 2678
I have just started learning groovy and I am reading "Groovy in Action". In this book I came across a statement that it doesn’t matter whether you declare or cast a variable to be of type int or Integer.Groovy uses the reference type ( Integer ) either way.
So I tried to assign null value to a variable with type int
int a = null
But it is giving me below exception
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)
Then I tried to assign null value to a variable with type Integer
Integer a = null
and it is working just fine.
Can anyone help me understand how groovy
behaves such way or the reason behind it?
Upvotes: 11
Views: 23962
Reputation: 23805
The core problem is that primitives can’t be null. Groovy fakes that out with autoboxing.
If you store a null
value in a number, you can’t store that in a int/long/etc
field. It’s not correct to convert a null number
to 0, since this might be valid values. Null
means that no value or choice has been made yet.
int
is a primitive type
and it is not considered as an object
. Only objects
can have a null
value while int
value can't be null
because It's a value type rather than a reference type
For primitive types
, we have fixed memory size i.e for int
we have 4 bytes
and null
is used only for objects
because there memory size is not fixed.
So by default we can use :-
int a = 0
Upvotes: 9
Reputation: 3016
Groovy uses wrapper types in all time when you call primitives
int a = 100
assert Integer == a.class
groovy takes int and wrap it into Integer before using it value But groovy cannot set int value to null, because variable is int(primitive type) but not Integer.
int a = 100
int b = 200
a + b not int + int, but Integer + Integer
Upvotes: 5
Reputation: 20699
As I understand it, Groovy uses the wrapper types if you use literals. For example:
def a = 11 // equivalent to Object a = 11. 11 is an java.lang.Integer
or
assert ['java.lang.Integer'] == [ 11, 22, 33 ]*.class*.name.unique()
Although if you use a specific type in your definition, the compiler has to perform casting.
You can do:
def a = 11
a = 'ssss'
but
int a = 11 // or int a
a = 'ssss'
gives GroovyCastException
.
This what you see in your case
Upvotes: 1