Scala inheriting a class with the same variable name

Why is scala complaining about the code below?

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

      

But it normal.

scala> class C(boo:Int)
defined class C

scala> case class D(far:Int, boo:Int) extends C(boo)
defined class D

      

+3


source to share


2 answers


var status: Int

will create accessor methods, something like

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

      



the case class creates these methods by default, so you have two methods with the same signature, and scala requires you to add a keyword override

when overriding methods.

without var

you create class fields and they are not overridden.

+5


source


I think the Http class should have val for status

so:



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

      

0


source







All Articles