Scala继承参数化构造函数 [英] Scala inherit parameterized constructor
问题描述
我有一个带有几个可选参数的抽象基类:
抽象案例类假设(
要求:布尔值= false,
onlyDays:Seq [Int] = Nil,
...
)延伸Something {...}
我是否真的需要使用附加关键字覆盖val
在上显式重复所有参数
案例类SomeHypothesis(
anotherArg:SomeType,
覆盖val要求:Boolean = false,
覆盖val onlyDays:Seq [Int] = Nil,
...
)扩展Hypothesis(
要求,
onlyDays,
...
){...}
或者是否存在类似
<$ p $的语法p>
案例类SomeHypothesis(anotherArg:SomeType,**)扩展假设(**){...}
我甚至不需要 anotherArg
,只是一种将所有关键字args传递给super con的方法结构。
我真的很喜欢Scala关于构造函数的想法,但是如果没有这个构造函数的语法,我'会很失望:(
你可以在继承的类中使用虚拟名称:
案例类SomeHypothesis(anotherArg:SomeType,rq:Boolean = false,odays:Seq [Int] = Nil)
扩展假设(rq,odays)
但你必须重复默认值。无需覆盖 val
。
编辑:
请注意,您的抽象类不应该是案例类。扩展案例类现在已弃用。您应该使用提取器代替抽象类:
abstract class SomeHypothesis(val request:Boolean)
object SomeHypothesis {
def unapply(o:Any):Option [Boolean] = o匹配{
case sh:SomeHypothesis =>一些(sh.request)
case _ =>无
}
}
I have an abstract base class with several optional parameters:
abstract case class Hypothesis(
requirement: Boolean = false,
onlyDays: Seq[Int] = Nil,
…
) extends Something {…}
Do i really need to explicitly repeat all parameters with the additional keywords override val
on top‽
case class SomeHypothesis(
anotherArg: SomeType,
override val requirement: Boolean = false,
override val onlyDays: Seq[Int] = Nil,
…
) extends Hypothesis(
requirement,
onlyDays,
…
) {…}
Or is there a syntax like
case class SomeHypothesis(anotherArg: SomeType, **) extends Hypothesis(**) {…}
I don’t even need anotherArg
, just a way to pass all keyword args to the super constructor.
I really like Scala’s idea about constructors, but if there isn’t a syntax for that one, I’ll be disappoint :(
You can just use a dummy name in the inherited class:
case class SomeHypothesis(anotherArg: SomeType, rq: Boolean = false, odays: Seq[Int] = Nil)
extends Hypothesis(rq, odays)
but you do have to repeat the default values. There is no need to override a val
.
EDIT:
Note that your abstract class should not be a case class. Extending case classes is now deprecated. You should use an extractor for you abstract class instead:
abstract class SomeHypothesis(val request: Boolean)
object SomeHypothesis {
def unapply(o: Any): Option[Boolean] = o match {
case sh: SomeHypothesis => Some(sh.request)
case _ => None
}
}
这篇关于Scala继承参数化构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!