djsumdog
djsumdog

Reputation: 2714

Simplify constructing a subclass from its parent in Scala

So I have a base class:

case class CSVRecord (
  val timestamp : String,
  val transactionId : String,
  val action : String,
  val fromMSISDN :String,
  val toMSISDN :String,
  val fromICCID :String,
  val toICCID :String,
  val finalState :String,
  val reason : String,
  val source : String
)

And it has a subclass of itself that I occasionally need to initialize with an instance of its parent. Is there a simpler way to do this? Right now I have to repeat every field and assign it again. Is there an easier/cleaner way to do this in Scala?

class Record (
  val id : Long,
  val batch_id : Long,

  timestamp : String,
  transactionId : String,
  action : String,
  fromMSISDN :String,
  toMSISDN :String,
  fromICCID :String,
  toICCID :String,
  finalState :String,
  reason : String,
  source : String

) extends     CSVRecord(timestamp,transactionId,action,fromMSISDN,toMSISDN,fromICCID,toICCID,finalState,reason,source) with KeyedEntity[Long] {
  def this() = this(0,0,"","","","","","","","","","")
  def this(id : Long, batch_id : Long, r : CSVRecord) = this(id,batch_id,r.timestamp,
    r.transactionId,r.action,r.fromMSISDN,r.toMSISDN,r.fromICCID,r.toICCID,r.finalState,r.reason,r.source)

  lazy val provisionings : OneToMany[Provisioning] = MWS.recordToProvisioning.left(this)
  lazy val batch : ManyToOne[Batch] = MWS.batchToRecord.right(this)
}

Upvotes: 1

Views: 60

Answers (2)

yǝsʞǝla
yǝsʞǝla

Reputation: 16422

You can't avoid specifying all constructor arguments. One "workaround" if it suits your needs would be to use def with implementation instead of val:

trait A {
  def a: Int = 1
  def b: String = "text"
}

class B extends A

This works only if you have mostly getters, not setters.

Combining fields together as @Mik378 suggested is a good solution too:

trait BaseType

case class SharedArgs(a: Int, b: String)

case class A(args: SharedArgs) extends BaseType

case class B(args: SharedArgs, anotherArg: Int) extends BaseType

Not only it reduces code duplication it also makes it easier to read the code - it's easy to get lost with so many args.

Upvotes: 1

Mik378
Mik378

Reputation: 22191

Why not gathering some related fields into Value Objects (case class)? This would greatly reduce the writing of your subclass.

Upvotes: 1

Related Questions