Scala类继承具有相同的变量名称

时间:2013-02-05 10:53:23

标签: scala inheritance

为什么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

2 个答案:

答案 0 :(得分:5)

var status: Int将创建访问器方法,类似于

def status() = this.status
def status(status: Int) {this.status = status}

case类默认创建这些方法,因此你有两个具有相同签名的方法,scala要求你在重写方法时添加override关键字。

没有var你只创建类字段而不会覆盖它们。

答案 1 :(得分:0)

我认为Http类必须具有状态值

所以:

scala> class Http(val status: Int)
defined class Http

scala> case class Post(url: String, data: String, override val status: Int) extends Http(status)
defined class Post