2014-02-28 60 views
1

构建从其父子类,所以我有一个基类:简化斯卡拉

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 
) 

而且它有其自身的子类,我偶尔需要与其父的一个实例初始化。有没有更简单的方法来做到这一点?现在我必须重复每个字段并重新分配。在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) 
} 
+0

'Record' extends'CSVRecord'?这不正好吗? – Mik378

+0

AFAIK你不能扩展一个case类 –

+0

你不能推荐'case class'扩展另一个'case class'(不是这个帖子的情况),因为可能会导致一些平等的奇怪问题。 – Mik378

回答

1

为什么不将相关字段收集到值对象(case class)?这将大大减少你的子类的写作。

1

您无法避免指定所有构造函数参数。一个“解决办法”,如果它适合您的需求将是使用def与实施,而不是val

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

class B extends A 

这只有你有大多的getter,setter方法没有。

结合领域在一起@ Mik378建议是一个很好的解决方案过于:

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 

它不仅减少了代码重复这也使得它更容易阅读的代码 - 很容易失去这么多ARGS得到。