Pointers in Scala
Scala supports references to values and objects within your program, which are similar to pointers in other languages. However, Scala doesn’t have explicit pointer types like Go does. Instead, it uses references for all non-primitive types.
We’ll show how references work in contrast to values with two functions: zeroval
and zeroref
. zeroval
has an Int
parameter, so arguments will be passed to it by value. zeroval
will get a copy of ival
distinct from the one in the calling function.
zeroref
in contrast takes a mutable reference to an integer. The value
property in the function body then accesses the current value of the referenced object. Assigning a value to value
changes the value of the referenced object.
zeroval
doesn’t change the i
in main
, but zeroref
does because it has a reference to the mutable object.
To run this Scala program:
Note that Scala doesn’t provide direct access to memory addresses like Go does with the &
operator. Instead, we use System.identityHashCode()
to get a unique identifier for the object, which serves a similar purpose in this context.
In Scala, all non-primitive types are reference types by default, so you don’t need to explicitly use pointers or reference operators. The language handles references automatically, which can make code cleaner but also requires careful consideration when dealing with mutable state.