1

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Why do you use new Object {} instead of simply new Object? It creates a new anonymous class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.