Pointers in Groovy
Our example demonstrates how references work in Groovy. We’ll show this with two functions: zeroval
and zeroref
.
def zeroval(val) {
val = 0
}
def zeroref(ref) {
ref.value = 0
}
def main() {
def i = 1
println "initial: $i"
zeroval(i)
println "zeroval: $i"
def wrapper = [value: i]
zeroref(wrapper)
i = wrapper.value
println "zeroref: $i"
println "reference: ${wrapper.toString()}"
}
main()
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.
def main() {
def i = 1
println "initial: $i"
We first print the initial value of i
.
zeroval(i)
println "zeroval: $i"
zeroval
doesn’t change the i
in main
, because it only has a copy of the value.
def wrapper = [value: i]
zeroref(wrapper)
i = wrapper.value
println "zeroref: $i"
zeroref
does change the value because it has a reference to the wrapper object containing i
.
println "reference: ${wrapper.toString()}"
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:
$ groovy pointers.groovy
initial: 1
zeroval: 1
zeroref: 0
reference: [value:0]
This example shows how Groovy handles value passing and object references, which is similar to how many other object-oriented languages work.