1

Given Foo:

class Foo {
  def getBar = new Bar

  class Bar {
    def baz = 3
  }
}

I'd like to be able to extend Foo, and override baz.
The simplest implementation I can think of is this:

class Foo2 extends Foo {
  override def getBar = new Bar2

  class Bar2 extends Bar {
    override def baz = 5
  }
}

but I'm wondering if there is a simpler way to achieve this. (getBar might contain a lot of code, and I don't won't to copy paste it with just a small change Bar -> Bar2)

I tried this:

class Foo2 {

  class Bar extends super.Bar {
    override def baz = 5
  }
}

But unfortunately it doesn't work
(new Foo2().getBar.baz == 3)

Any other ideas?

Update: fixed compilation error as mentioned in the responses

lev
  • 3,986
  • 4
  • 33
  • 46

2 Answers2

2

Overriding classes requires something like virtual classes. But they don't exist, so that is impossible.

I would advise not to do class Bar extends super.Bar, because then you're just shadowing the Bar class from Foo, which will only cause confusion. I think the best you can do is provide a method in Foo that constructs a Bar, as an alias for the real constructor. Because methods can be overridden, constructors can't.

class Foo {
  final def getBar = {
    val i: Int = doLotsOfComputations1()
    val s: String = doLotsOfComputations2()
    initBar(i, s)
  }

  protected def initBar(i: Int, s: String): Bar = new Bar(i, s)

  protected class Bar(i: Int, s: String) {
    def baz = 3
  }
}

class Foo2 extends Foo {
  override protected def initBar(i: Int, s: String) = new Bar2(i, s)

  protected class Bar2(i: Int, s: String) extends Bar(i, s) {
    override def baz = 5
  }
}
Community
  • 1
  • 1
Jasper-M
  • 14,966
  • 2
  • 26
  • 37
1

You are missing override

  class Foo {
def getBar = new Bar

class Bar {
  def baz = 3
}}

  class Foo2 extends Foo {
override def getBar = new Bar2

class Bar2 extends Bar {
  override def baz = 5
}}
PawelN
  • 848
  • 7
  • 17