案例类中的产品继承
我有一些扩展公共超类的案例类,我想使用 productElement
方法访问超类中的字段(我尝试将基类声明为案例类,但我收到了可怕的警告关于案例类继承的危险,但不起作用)。
我可以想象这样的解决方案:
abstract class A(a: Int) extends Product {
def productArity = 1
def productElement(n: Int) = if (n == 0) a else throw new IndexOutOfBoundsException
}
case class B(b: Int) extends A(1) {
def productArity = super.productArity + 1
def productElement(n: Int) = if (n < super.productArity) super.productElement(n) else ....
}
但它变得如此丑陋,我什至无法完成。
有人知道更好的解决方案吗?
I have some case classes that extend a common superclass and I'd like to access fields from the superclass using productElement
method (I've tryed to declare base class as a case class but I get a frightening warning about the dangers of inheritance of case classes and yet doesn't work).
I can imagine some solution like this:
abstract class A(a: Int) extends Product {
def productArity = 1
def productElement(n: Int) = if (n == 0) a else throw new IndexOutOfBoundsException
}
case class B(b: Int) extends A(1) {
def productArity = super.productArity + 1
def productElement(n: Int) = if (n < super.productArity) super.productElement(n) else ....
}
but it was getting so ugly that I can't even finish.
Does anybody know a better solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Scala 主干中,很多工作已经为您完成:案例类现在扩展了适当的 ProductN 特征。然而,只有案例类直接(即非继承)成员包含在产品中,因此,如果您需要包含来自超类型的成员,则它们必须在超类型中是抽象的,并在案例类中给出具体的实现。
这是一个 REPL 会话(Scala 主干,2.10.0.r25951-b20111107020214),
In Scala trunk a lot of this is done for you already: case classes now extend the appropriate ProductN trait. Only case class direct (ie. not inherited) members are included in the product however, so if you need to include members from a super type, they would have to be abstract in the super type and given a concrete implementation in the case class.
Here's a REPL session (Scala trunk, 2.10.0.r25951-b20111107020214),
我能得到的最接近的是不在 A 中实现任何内容
The closest I can get is to not implement anything in A