Weird Function Object Behavior in Scala - Mutable Function Variables are Resetting -
this functor represents act of moving associated (mutable) x-position , y-position:
final class moving(var xpos: int, var ypos: int) extends function2[int, int, unit] { override def apply(dx: int, dy: int): unit = { xpos += dx ypos += dy println("xpos: " + xpos + " ypos: " + ypos) } }
the problem not behave expected. when run code:
def move = new moving(0, 0) def main(args: array[string]) { move.apply(1,1) move.apply(2,2) move.apply(3,3) }
i output:
xpos: 1 ypos: 1 xpos: 2 ypos: 2 xpos: 3 ypos: 3
the x-position , y-position appear going initial value before being modified. want output this:
xpos: 1 ypos: 1 xpos: 3 ypos: 3 xpos: 6 ypos: 6
why isn't function behaving expected?
* solution *
val motion = new moving(0, 0) def move = motion // returns function object def main(args: array[string]) { move.apply(1,1) move.apply(2,2) move.apply(3,3) }
it's because declare move
method, not field. means each time reference move
, create new instance of moving
class act on.
change code this:
val move = new moving(0, 0)
which uses val
instead of def
, , you'll same instance every time.
the confusion comes blurred line between functions , objects in scala. moving
class function, since preserves state need make sure act on same instance of every time. using def
in case declares method returns function, rather giving same function each time.
Comments
Post a Comment