Scala继承参数化构造函数

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (15)

我有一个带有几个可选参数的抽象基类:

abstract case class Hypothesis(
    requirement: Boolean = false,
    onlyDays:   Seq[Int] = Nil,
    …
) extends Something {…}

加上附加关键字override val二次

case class SomeHypothesis(
    anotherArg: SomeType,
    override val requirement: Boolean = false,
    override val onlyDays:   Seq[Int] = Nil,
    …
) extends Hypothesis(
    requirement,
    onlyDays,
    …
) {…}

或者是否有类似于

case class SomeHypothesis(anotherArg: SomeType, **) extends Hypothesis(**) {…}

我甚至不需要anotherArg,这只是将所有关键字args传递给超级构造函数的一种方法。

提问于
用户回答回答于

只需在继承的类中使用虚拟名称:

case class SomeHypothesis(anotherArg: SomeType, rq: Boolean = false, odays: Seq[Int] = Nil)
extends Hypothesis(rq, odays)

但是你必须重复默认值。不需要覆盖val...

编辑:

abstract class SomeHypothesis(val request: Boolean)

object SomeHypothesis {
  def unapply(o: Any): Option[Boolean] = o match {
    case sh: SomeHypothesis => Some(sh.request)
    case _ => None
  }
}
用户回答回答于

在我看来,默认值的策略不属于基类,而应该放在具体的类上。相反,我要做以下几点:

trait Hypothesis {
  def requirement: Boolean
  def onlyDays: Seq[Int]
  /* other common attributes as necessary */
}

case class SomeHypothesis(anotherArg: SomeType,
                          requirement: Boolean = false,
                          onlyDays: Seq[Int] = Nil)
  extends Hypothesis

的案例类字段。SomeHypothesis才能满足假设特征的要求。

正如其他人所说的,仍然可以使用提取器对常见部分进行模式匹配:

object Hypothesis {
  def unapply(h: Hypothesis): (Boolean, Seq[Int]) = (h.requirement, h.onlyDays)
}

扫码关注云+社区