如何在构造函数中初始化父案例类参数

时间:2016-05-25 16:29:54

标签: scala

以下代码按预期工作:

scala> case class Family(numPeople: Int)
defined class Family

scala> class MyFamily(val numBoys: Int, val numGirls: Int) extends Family(numBoys + numGirls)
defined class MyFamily

scala> val f = new MyFamily(2, 3)
f: MyFamily = Family(5)

scala> f.numPeople
res5: Int = 5

但是,如果numBoys + numGirls部分更复杂并且需要多行,那么稍后设置numPeople值有一些整洁的方法吗?我尝试过这样做,但Family(0)部分看起来不对:

scala> class MyComplexFamily(val numBoys: Int, val numGirls: Int) extends Family(0) {
     | override val numPeople = numBoys + numGirls
     | }
defined class MyComplexFamily

scala> val f3 = new MyComplexFamily(3, 4)
f3: MyComplexFamily = Family(7)

1 个答案:

答案 0 :(得分:5)

尽管可能,但不鼓励使用case类继承 - scala编译器为case类生成equalshashCode方法,如果你打算能够区分MyComplexFamily(3, 4)Family(7),你遇到了麻烦。

但是,如果存在MyComplexFamily的唯一原因是对输入数据执行某些处理,则首选方法是在案例类的伴随对象中定义替代构造函数。

case class Family(numPeople: Int)
object Family {
  def ofBoysAndGirls(numBoys: Int, numGirls: Int): Family = Family(numBoys + numGirls)
}

另一种方法是将特征提取到特征中并在两个类中扩展它 - 这样您就不需要初始化参数。

trait Family {
  def numPeople: Int
}
case class Family(numPeople: Int) extends Family
case class ComplexFamily(numBoys: Int, numGirls: Int) extends Family {
  val numPeople = numBoys + numGirls
}