So I have the following scenario. First a class hierarchy A <- B <- C
trait A
trait B extends A
class C extends B
I also have a class that has a generic parameter defined as [T <: A]
class Foo[T <: A]
This class defines two methods that accept objects of type T
def single(t: T): Bar
def multiple(lt: List[T]): Bars
If the objects t
and lt
are of a type derived from B both, of these methods call another method that takes t
and lt
(mapping over its elements), does some modification to it (which depends on the type itself) and spits the same object out
def update[P <: B](op: P, item: Item): P = {
if (item.field1..) op.field1 = item.field1
if (item.field2..) op.field2 = item.field2
...
op match {
case c: C =>
if (item.field123 ...) c.field123 = item.field123
}
op
}
I don't like the way this method is right now as it does mutation on the objects. As I am following a functional programming style I have managed to keep the codebase immutable and composable.
I would prefer to push the field assignments to constructors and build up the objects based on their parent class but due to Scala's auxiliary constructor calling scheme I cannot find a way to do this. Another way would have been to have a case class and use the copy constructor but I cannot do that because I need to keep A, B and C extendable.
I hope I managed to describe my scenario well enough. If you need some more clarification - please ask. I would appreciate any help with this one.