I’m aware that case class inheritance is deprecated in Scala, but for the sake of simplicity, I’ve used it in the following example:
scala> case class Foo(val f: String) { def foo(g: String): Foo = { this.copy(f=g) }}
defined class Foo
scala> case class Bar(override val f: String) extends Foo(f)
warning: there were 1 deprecation warnings; re-run with -deprecation for details
defined class Bar
scala> Bar("F")
res0: Bar = Foo(F)
scala> res0.foo("G")
res1: Foo = Foo(G)
So far, so good. What I really want, though, is to be able to write a method foo() in Foo that returns an object of type Bar when called on an object of type Bar, without having to reimplement the method in class Bar. Is there a way to do this in Scala?
Note: This does not create a new object but re-uses the
thisobject. For general use, see paradigmatic’s answer.For some reason, it does not work together with the
case class’scopymethod. (But admittedly, sincecase classinheritance should not be done anyway, the problem does not occur.). But for any other method, you do it withthis.type.If you need the self-type variance in method arguments and method bodys (as opposed to return-type-only variance), you will need to go one step further and define
This will allow you to add proper method bodies to the
trait. (See: proper class hierarchy for 2D and 3D vectors)