Pointers in Groovy
Our example demonstrates how references work in Groovy. We’ll show this with two functions: zeroval
and zeroref
.
zeroval
has a parameter that’s passed by value. zeroval
will get a copy of val
distinct from the one in the calling function.
zeroref
, in contrast, takes an object reference. Modifying the value
property of this object affects the original object.
The &
syntax for getting memory addresses doesn’t exist in Groovy, so we use a wrapper object to simulate reference behavior.
We first print the initial value of i
.
zeroval
doesn’t change the i
in main
, because it only has a copy of the value.
zeroref
does change the value because it has a reference to the wrapper object containing i
.
We can print the string representation of the wrapper object.
When we run the program, we see that zeroval
doesn’t change the original variable, but zeroref
does:
This example shows how Groovy handles value passing and object references, which is similar to how many other object-oriented languages work.