0

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

1 Answer 1

2

productIterator is defined on scala.Product, which all case classes extend, so you can just write

def extract(e: Product): Array[Any] = ...

It may or may not be a problem that you can call this method on all Products, not just your models. If you want to avoid this, just make BaseModel in your last snippet extend Product:

abstract class BaseModel() extends Product

Look up abstract classes in case you aren't familiar with this term.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.