Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subclass an object with a var in its primary constructor

Tags:

scala

I'm wanting to do something like this:

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)

but the compiler doesn't like it.

(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) {

Adding override on updateCount doesn't work either. What's the clean way to do this?

like image 323
Trenton Avatar asked Nov 17 '09 09:11

Trenton


2 Answers

You don't need to declare the var in the subclass constructor signature:

class B (val name: String, /* note no var */ updateCount: Int) extends A(updateCount) {
  //...
}

This also extends to classes with vals in their constructors also:

scala> class C(val i: Int)
defined class C

scala> class D(j: Int) extends C(j)
defined class D
like image 100
oxbow_lakes Avatar answered Sep 20 '22 06:09

oxbow_lakes


You need to avoid having the identifier declared for B shadowing the identifier declared for A. The easiest way to do that is to chose a different name. If, however, you really, really don't want to do that, here is an alternative:

class B (val name: String, updateCount: Int) extends A(updateCount) {
  self: A =>
  def inc(): Unit = {
    self.updateCount = self.updateCount + 1
  }
}

And, by the way, drop the var from B declaration.

like image 23
Daniel C. Sobral Avatar answered Sep 21 '22 06:09

Daniel C. Sobral