派生 Scala 案例类,其成员变量与基类相同 [英] Derived Scala case class with same member variables as base

查看:32
本文介绍了派生 Scala 案例类,其成员变量与基类相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的方法来做到这一点?

Is there a nicer way of doing this?

scala> case class A(x : Int)
defined class A

scala> case class B(override val x : Int, y : Int) extends A(x)
defined class B

我用 B 扩展了 A 并添加了一个额外的成员变量.最好不要在 x 之前写 override val.

I'm extending A with B and adding an extra member variable. It would be nice not to have to write override val before the x.

推荐答案

我强烈建议不要从案例类继承.它对 equals 和 hashCode 有惊人的影响,在 Scala 2.8 中已被弃用.

I would strongly advise not to inherit from a case class. It has surprising effects on equals and hashCode, and has been deprecated in Scala 2.8.

相反,在特征或抽象类中定义 x.

Instead, define x in a trait or an abstract class.

scala> trait A { val x: Int }
defined trait A

scala> case class B(val x: Int, y: Int) extends A
defined class B

http://www.scala-lang.org/node/3289

http://www.scala-lang.org/node/1582

这篇关于派生 Scala 案例类,其成员变量与基类相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆