I have two case classes that inherit from an abstract base class. I want to define some methods on the abstract base class that use the copy methods on the inheriting case classes (and so return an instance of the child class.) Is there a way to do this using self types?
Example code:
abstract class BaseClass(a: String, b: Int) {
this: case class => //not legal, but I'm looking for something similar
def doubleB(newB: Int) = this.copy(b = b * 2) //doesn't work because BaseClass has no copy
}
case class HasC(a: String, b: Int, c: Boolean) extends BaseClass(a, b) {
def doesStuffWithC(newC: Boolean) = {
...
}
}
case class HasD(a: String, b: Int, D: Double) extends BaseClass(a, b) {
def doesStuffWithD(newD: Double) = {
...
}
}
I’ve figured out how to get the result I want thanks to this question:
How to use Scala's this typing, abstract types, etc. to implement a Self type?
but it involves adding a makeCopy method to BaseClass and overriding it with a call to copy in each of the child case classes, and the syntax (especially for the Self type) is fairly confusing. Is there a way to do this with Scala’s built in self typing?
You can’t do what you want because
copyneeds to know about all the possible parameters. So even if case classes inherited fromCopyable, it wouldn’t be thecopyyou needed. Also, if you’re going to keep the types straight, you’ll be thwarted by Scala’s lack of a “MyType“. So you can’t just extend a base class. However, you could add an abstract method and type annotation:And then you can:
This extra work will be worth it if you have a lot of shared functionality that depends on the ability to copy just
b(either many methods, or a small number of complicated methods)–that is, this solves the DRY issue. If instead you want to abstract overHasCand other derived classes, you can either useBaseClass[_]or add yet another level that definessetB(b0: Int): BaseBaseor simply forget the type parameterization and useBaseClassas the return type (but recognize thatHasCcannot useBaseClassmethods and still retain its type identity).