简体   繁体   English

Scala中缀运算符工作奇怪

[英]Scala infix operator working weird

I was trying to replicate an example from the book Scala in Depth. 我试图复制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 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. 这看起来不太正确...我也试过this.x = this.x - other.x ,和y一样。 I got a different result but not the result I wanted. 我得到了不同的结果,但不是我想要的结果。 What's wrong with the program?? 程序有什么问题? How can I fix it?? 我该怎么解决?

You assign x 2 times and y 0 times in - , so the subtraction doesn't work. -指定x 2次和y 0次,因此减法不起作用。 Change second line of - method from x = y - other.y to y = y - other.y . 改变-方法的第二行从x = y - other.yy = y - other.y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM