定义一个不平凡的 Scala 案例类是否合适?
我今天定义了一个 Scala 类,我认为“我需要一个 equals
方法和一个 hashCode
方法;并且一个 copy
方法是我也会把它变成一个案例类。”我的类已经有一堆其他代码,而且绝不是微不足道的。
很好,一切都有效,但是当教科书处理案例类时,所有示例都将它们定义为用作值类或“数据传输对象”。定义一个非平凡的案例类是否合适?上面描述的思维过程可以吗?还是我需要以不同的方式思考案例类?
I'm defining a Scala class today, and I think "I need an equals
method and a hashCode
method; and a copy
method would be handy too. I'll turn this into a case class." My class already has a bunch of other code, and is in no way trivial.
So fine, it all works and everything, but when the text books deal with case classes, all of the examples define them for use as value classes or 'data transfer objects'. Is it appropriate to define a non-trivial case class? Is the thought process described above OK, or do I need to think of case classes differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
case 类
提供了基于主构造函数参数的equals
、hashCode
和toString
方法,所有这些方法都是也变成了val
。此外,对象伴侣还获得一个apply
和一个unapply
方法,同样基于主构造函数参数。此外,
case 类
继承自Serialized
和Product
,并且不应由其他类扩展。如果所有这些都适合您的类,那么请随意将其声明为“案例类”。
A
case class
provides,equals
,hashCode
andtoString
methods based on the main constructor parameters, all of which are turned intoval
too. In addition, the object companion gets anapply
and anunapply
methods, again based on the main constructor parameters.Also, a
case class
inherits fromSerializable
and fromProduct
, and should not be extended by other classes.If all of these things are appropriate for your class, then feel free to declare it as a `case class'.
随意,只要它没有后代。扩展案例类是一个坏主意。
Feel free, provided it doesn't have descendants. Extending case classes is a bad idea.