2013-02-05 68 views
3

爲什麼scala會抱怨下面的代碼?具有相同變量名的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 

回答

5

var status: Int將創建存取方法,像

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

案例類創建這些方法默認情況下,所以你有兩個具有相同簽名和方法的方法在重寫方法時要求您添加override關鍵字。

沒有var你只能創建類字段,它們不會被覆蓋。

0

我認爲一流的Http必須有一個VAL的狀態

等:

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 
相關問題