Azeli
Azeli

Reputation: 748

Scala: Can object Reference pass through nested functions?

In Scala, one passes pointers to objects, not the objects themselves. Is it correct to say then, that there is no problem with passing an object pointer through nested functions as below, i.e. there wont be layers of objects allocated?

case class Parameters(name: String, id: String, values: Array[Double])
case class Context(id: String, a: Double, b: Double, c: Double)

and

def myFunc(par: Parameters, ctx: Context): Unit = {
  //..do stuff
  for (i<- 1 to ITERATIONS) {
     otherFunctions.resolve(par, ctx)
}
object otherFunctions {
   def resolve(params: Parameters, ctx: Context): Unit = {
      //do more ...
      val x: Int = {...}
      calculate(params.values, ctx.a, ctx.b, x)
   }
   def calculate(array: Array[Double], b: Double, c: Double, x: Int) = ...
   }
}

In this case when myFunc is called on instances of Parameters and Context, since the default is call-by-value, scala "evaluates the parameters first". my confusion is whether "evaluated" in this sense is the copying of objects, or just the pointers. that would clearly effect whether or not I pull parameters out before the for expression.

Upvotes: 1

Views: 325

Answers (1)

dhg
dhg

Reputation: 52681

The objects are not copied, only the pointers are.

Here's an example showing that an allocated object, while passed through a series of function calls, always points to exactly the same object in memory (the memory address gets printed):

def g(o: Object) {
    println(System.identityHashCode(o))
}
def h(o: Object) {
    println(System.identityHashCode(o))
    g(o)
}
h(new Object)

prints:

1088514451
1088514451

Note that this is completely different from call-by-name, where the "evaluation" will allocate a new object each time it is called:

def g(o: => Object) {
    println(System.identityHashCode(o))
}
def h(o: => Object) {
    println(System.identityHashCode(o))
    g(o)
}
h(new Object)

prints:

2144934647
108629940

Upvotes: 2

Related Questions