I'm new to Scala and have had a look around at similar questions, but am not certain they're the same as my question - apologies if I'm wrong.
Essentially, I am unsure how to refactor this code
case class ModelX(a: Int, b: Int)
case class ModelY(b: Int, c: Int)
case class ModelZ(a: Int, c: Int)
def extract_x(e: ModelX): Array[Any] = e.productIterator.map {
case op: Option[_] => op.getOrElse(null)
case v => v
}.toArray
def extract_y(e: ModelY): Array[Any] = e.productIterator.map {
case op: Option[_] => op.getOrElse(null)
case v => v
}.toArray
def extract_z(e: ModelZ): Array[Any] = e.productIterator.map {
case op: Option[_] => op.getOrElse(null)
case v => v
}.toArray
for any number of models (as I have have more than 3). The reason I am doing this, is that I can extract a row from Cassandra into one of these models, then I need to pass it to an Array[Any] as I have serialisation methods available to me after this point, and can work with the returned values more comfortably in my language of choice.
I have tried defining a base class that ModelX|Y|Z extend, such that I could just apply extract on the base class, but productIterator is not available to the base class. If that was a bad explanation, what I tried/wanted to do was this:
class BaseModel()
case class ModelX(a: Int, b: Int) extends BaseModel
case class ModelY(b: Int, c: Int) extends BaseModel
case class ModelZ(a: Int, c: Int) extends BaseModel
def extract(e: BaseModel): Array[Any] = e.productIterator.map {
case op: Option[_] => op.getOrElse(null)
case v => v
}.toArray
I'm very new to Scala, so I imagine I've missed something obvious. Any help here would be appreciated.
Akhil