windweller
windweller

Reputation: 2385

Scala infix operator working weird

I was trying to replicate an example from the book Scala in Depth. The example is to demonstrate how mutability is bad and people should prefer immutability.

However, my little experiment has failed and the program exhibits weird behaviors. Here is my program:

class Vector2D(var x: Double, var y: Double) {
  def -(other:Vector2D) = {
    x = x - other.x
    x = y - other.y
    this
  }
  def magnify(amt: Double) : Vector2D = {
    x *= amt
    y *= amt
    this
  }
  override def toString = s"Vector2D($x, $y)"
}

The second function is copied from the book. I had to add two functions to make the results look like what the book demonstrated.

The program stopped working on the first function: -

I used Scala REPL:

scala> val x = new Vector2D(1,1)
x: Vector2D = Vector2D(1.0, 1.0)

scala> val y = new Vector2D(-1, 1)
y: Vector2D = Vector2D(-1.0, 1.0)

scala> x - y
res0: Vector2D = Vector2D(0.0, 1.0)

This does not look very correct...also I tried this.x = this.x - other.x, same as y. I got a different result but not the result I wanted. What's wrong with the program?? How can I fix it??

Upvotes: 0

Views: 154

Answers (1)

Display Name
Display Name

Reputation: 8128

You assign x 2 times and y 0 times in -, so the subtraction doesn't work. Change second line of - method from x = y - other.y to y = y - other.y.

Upvotes: 2

Related Questions