I have an abstract class which I extend and make numerous case classes. Now I want to copy instances of those case classes just changing first parameter, so I use case class
Using only standard scala there is no such generic copy method on abstract (super) class: how would it know how all subclasses can be cloned/copied? Especially that new subclasses could be added in the future.
To my knowledge, the two main approaches to implement such abstract method are:
1) make a function that match-case on all subclasses:
def clone(o: Organism) = o match {
case o: Octopus => o.copy(legs = -1)
case f: Frog => f.copy(legs = -1)
}
Then each time a new subclass is added, it needs to be added in this functions. This is most appropriate for use with sealed abstract class.
2) add a makeClone method to the abstract API (the name clone being reserved):
abstract class Organism(legs: Int){
def makeClone(legNumber: Int): Organism
}
case class Octopus(legs: Int, weight: Double) extends Organism(legs) {
def makeClone(legNumber: Int) = this.copy(legs = legNumber)
}
Note that while the function in (1) always returns an Organism, here the method Octopus.makeClone returns an Octopus.