Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala compiler error due to constructor parameter (property) having same name in both base and derived class and used in derived method

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?".

like image 805
Derek Mahar Avatar asked Feb 28 '23 22:02

Derek Mahar


2 Answers

class A(var a: Int)
class B(a: Int) extends A(a) {
  def inc(value: Int) { (this: A).a += value }
}
like image 152
Mitch Blevins Avatar answered Mar 03 '23 02:03

Mitch Blevins


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.

like image 27
Daniel C. Sobral Avatar answered Mar 03 '23 01:03

Daniel C. Sobral