Scala:"reassignment to val" x,但 x 是 var

Scala: "reassignment to val" x, but x is var

我有如下一段代码

class A(var x: Int, var y: Int){

}

class B(x: Int, y: Int) extends A(x,y){

    def setX(xx: Int): this.type = {
        this.x = xx
        this
    }
}

但出现以下错误:

error: reassignment to val this.x = xx ^

我不知道发生了什么,因为 x 和 y 应该是变量。这样做的正确方法是什么?

成员变量的名称与构造函数参数的名称发生冲突。

明显的解决方法编译得很好:

class A(var x: Int, var y: Int)

class B(cx: Int, cy: Int) extends A(cx, cy) {

    def setX(xx: Int): this.type = {
        this.x = xx
        this
    }
}

这个问题似乎不是新的,这里是链接to a forum entry from 2009. It has a posting with literally the same error message in the same situation

根本原因是构造函数参数可以自动转换为私有vals,因为它们可以从对象的方法中引用:

class B(cx: Int, cy: Int) {
  def foo: Int = cx
}