I have the following piece of code
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
}
}
but it gives the following error:
error: reassignment to val this.x = xx ^
I don't know whats happening since x and y should be variables. WHat's the correct way of doing this?
There is a collision of the names of member variables with the names of the constructor arguments.
The obvious workaround compiles just fine:
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
}
}
The issue doesn't seem to be new, here is a llink to a forum entry from 2009. It has a posting with literally the same error message in the same situation.
The root cause is that constructor arguments can be automatically converted into private val
s, because they can be referenced from the methods of the object:
class B(cx: Int, cy: Int) {
def foo: Int = cx
}