运维开发网

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

运维开发网 https://www.qedev.com 2020-05-18 14:49 出处:网络 作者:运维开发网整理
我想做这样的事情: 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"
我想做这样的事情:

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)

但编译器不喜欢它.

(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) {

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

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

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

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

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

scala> class D(j: Int) extends C(j)
defined class D
0

精彩评论

暂无评论...
验证码 换一张
取 消