为什么 scala 会提示以下代码?
scala> class Http(var status: Int)
defined class Http
scala> case class Post(url: String, data: String, status: Int) extends Http(status)
<console>:8: error: overriding variable status in class Http of type Int;
value status needs `override' modifier
case class Post(url: String, data: String, status: Int) extends Http(status)
^
scala> case class Post(url: String, data: String, sta: Int) extends Http(sta)
defined class Post
但这运行正常。
scala> class C(boo:Int)
defined class C
scala> case class D(far:Int, boo:Int) extends C(boo)
defined class D
最佳答案
var status: Int
将创建访问器方法,例如
def status() = this.status
def status(status: Int) {this.status = status}
case 类默认创建这些方法,所以你有两个具有相同签名的方法,scala 要求你在覆盖方法时添加 override
关键字。
如果没有 var
,您只会创建类字段,它们不会被覆盖。
关于具有相同变量名的 Scala 类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14705801/