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.

def zeroval(ival: Int): Unit = {
  ival = 0 // This will not affect the original value
}

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.

def zeroref(iref: scala.collection.mutable.ArrayBuffer[Int]): Unit = {
  iref(0) = 0
}

import scala.collection.mutable.ArrayBuffer

object PointersExample {
  def main(args: Array[String]): Unit = {
    val i = ArrayBuffer(1)
    println(s"initial: ${i(0)}")

    zeroval(i(0))
    println(s"zeroval: ${i(0)}")

    zeroref(i)
    println(s"zeroref: ${i(0)}")

    // In Scala, we don't have direct access to memory addresses
    // But we can print the object's hash code as a unique identifier
    println(s"object identifier: ${System.identityHashCode(i)}")
  }
}

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:

$ scala PointersExample.scala
initial: 1
zeroval: 1
zeroref: 0
object identifier: 1234567890

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.