定义一个非平凡的 Scala 案例类是否合适? [英] Is it appropriate to define a non-trivial Scala case class?

查看:32
本文介绍了定义一个非平凡的 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?

推荐答案

一个case class提供,equalshashCodetoString 方法基于主要的构造函数参数,所有这些都变成了val.此外,对象伙伴获得一个 apply 和一个 unapply 方法,同样基于主构造函数参数.

A case class provides, equals, hashCode and toString methods based on the main constructor parameters, all of which are turned into val too. In addition, the object companion gets an apply and an unapply methods, again based on the main constructor parameters.

此外,case class 继承自 SerializableProduct,不应被其他类扩展.

Also, a case class inherits from Serializable and from Product, 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'.

这篇关于定义一个非平凡的 Scala 案例类是否合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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