Short of renaming the constructor parameter in the primary constructor of class B
, what change can I make to the following code (without changing its function) so that Scala will compile it successfully?
Example:
class A(var a: Int)
class B(a: Int) extends A(a) {
def inc(value: Int) { this.a += value }
}
Error:
$ scala construct.scala
construct.scala:3: error: reassignment to val
def inc(value: Int) { this.a += value }
^
one error found
I raised this question in an answer to my previous question, "In Scala, how do you define a local parameter in the primary constructor of a class?".
class A(var a: Int)
class B(a: Int) extends A(a) {
def inc(value: Int) { (this: A).a += value }
}
Another alternative:
class A(var a: Int)
class B(a: Int) extends A(a) {
self: A =>
def inc(value: Int) { self.a += value }
}
This might work better for more extensive cases, as you can use self
(or whatever other name you choose) throughout the body of the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With