wipman wipman - 2 months ago 14
Scala Question

In-function transformation side-effects on input arguments

I have something like this:

object MyObject {
var element1 /**/
var element2 /**/
var myOtherObject: OtherObject = new OtherObject
}

object MyOtherObject {
var something1 /**/
var something2 /**/
var myList: List[T] = List()
}

def myUpdateFunction(iMyObject: MyObject) : SomeObject = {
var myCopiedObject = iMyObject

myCopiedObject.myList.dropRight
/*checkpoint*/

val myAwesomeOtherObject = new MyOtherObject
/*perform multiple tasks to update myAwesomeOtherObject members*/

myAwesomeOtherObject
}


When I check
myUpdateFunction
execution on the "checkpoint" commented line, I observe my
myCopiedObject.myList
has successfully been transformed, but that my
iMyObject
has too, ie.
iMyObject.myList
got truncated by one.

I do not understand how this can happen.

Any clue, anyone?

By the way, I am using
spark

Answer

It happens because you're just assigning the same object to another reference. myCopiedObject is not a copy of your object. You should write a method, that will create a new instance of MyObject using the same values as iMyObject holds.

Comments