fly*_*eep 24 inheritance constructor scala
我有一个带有几个可选参数的抽象基类:
abstract case class Hypothesis(
requirement: Boolean = false,
onlyDays: Seq[Int] = Nil,
…
) extends Something {…}
Run Code Online (Sandbox Code Playgroud)
我是否真的需要在顶部使用附加关键字override val明确重复所有参数‽
case class SomeHypothesis(
anotherArg: SomeType,
override val requirement: Boolean = false,
override val onlyDays: Seq[Int] = Nil,
…
) extends Hypothesis(
requirement,
onlyDays,
…
) {…}
Run Code Online (Sandbox Code Playgroud)
或者是否有类似的语法
case class SomeHypothesis(anotherArg: SomeType, **) extends Hypothesis(**) {…}
Run Code Online (Sandbox Code Playgroud)
我甚至不需要anotherArg,只是将所有关键字args传递给超级构造函数的方法.
我真的很喜欢Scala关于构造函数的想法,但是如果没有这个的语法,我会很失望的:(
axe*_*l22 12
您可以在继承的类中使用虚拟名称:
case class SomeHypothesis(anotherArg: SomeType, rq: Boolean = false, odays: Seq[Int] = Nil)
extends Hypothesis(rq, odays)
Run Code Online (Sandbox Code Playgroud)
但你必须重复默认值.没有必要覆盖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
}
}
Run Code Online (Sandbox Code Playgroud)
在我看来,默认值的策略不属于基类,而应该继续使用具体的类.我会改为做以下事情:
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
Run Code Online (Sandbox Code Playgroud)
案例类字段SomeHypothesis将满足假设特征的要求.
正如其他人所说,你仍然可以在公共部分使用提取器进行模式匹配:
object Hypothesis {
def unapply(h: Hypothesis): (Boolean, Seq[Int]) = (h.requirement, h.onlyDays)
}
Run Code Online (Sandbox Code Playgroud)