Randall, your answers explain why the Scala compiler complains when I introduce a method inc
that increments the property a
, but also change the name of the parameter in the class B
constructor to match that of the parameter in the class A
constructor:
class A(var a: Int)
class B(a: Int) extends A(a) {
def inc(value: Int) { this.a += value }
}
Scala compiler output:
$ scala construct.scala
construct.scala:3: error: reassignment to val
def inc(value: Int) { this.a += value }
^
one error found
Scala complains because class B
must now have a private, read-only property a
due to the reference to a
in inc
. Changing B(a: Int)
to B(var a: Int)
generates a different compiler error:
construct.scala:2: error: error overriding variable a in class A of type Int;
variable a needs `override' modifier
class B(var a: Int) extends A(a) {
^
one error found
Adding override
doesn't help, either:
construct.scala:2: error: error overriding variable a in class A of type Int;
variable a cannot override a mutable variable
class B(override var a: Int) extends A(a) {
^
one error found
How can I use the same name in the parameter in the primary constructor of B
as the property defined in the primary constructor of the base class A
?