gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:32:26 25 4
gpt4 key购买 nike

我想做这样的事情:

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 的类s 在他们的构造函数中也:
scala> class C(val i: Int)
defined class C

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

关于scala - 如何在其主构造函数中使用 var 子类化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1747762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com