如何在主构造函数中使用var子类化对象

Tre*_*ton 7 scala

我想做这样的事情:

class A (var updateCount: Int) {
}

class B (val name: String, var updateCount: Int) extends A(updateCount) {
  def inc(): Unit = {
    updateCount = updateCount + 1
  }
}

var b = new B("a", 10)
println(b.name)
println(b.updateCount)

b.updateCount = 9999
b.inc
println(b.updateCount)
Run Code Online (Sandbox Code Playgroud)

但编译器不喜欢它.

(fragment of extend.scala):5: error: error overriding variable updateCount in class A of type Int;
 variable updateCount needs `override' modifier
class B (val name: String, var updateCount: Int) extends A(updateCount) {
Run Code Online (Sandbox Code Playgroud)

在updateCount上添加覆盖也不起作用.干净的方法是什么?

oxb*_*kes 7

您不需要var在子类构造函数签名中声明:

class B (val name: String, /* note no var */ updateCount: Int) extends A(updateCount) {
  //...
}
Run Code Online (Sandbox Code Playgroud)

这也扩展到val了构造函数中带有s的类:

scala> class C(val i: Int)
defined class C

scala> class D(j: Int) extends C(j)
defined class D
Run Code Online (Sandbox Code Playgroud)