声明 Scala 案例类有哪些缺点? [英] What are the disadvantages to declaring Scala case classes?
问题描述
如果您编写的代码使用了许多漂亮的、不可变的数据结构,那么案例类似乎是天赐之物,只需一个关键字即可免费为您提供以下所有功能:
If you're writing code that's using lots of beautiful, immutable data structures, case classes appear to be a godsend, giving you all of the following for free with just one keyword:
- 默认情况下一切都是不可变的
- 自动定义的吸气剂
- 体面的 toString() 实现
- 符合 equals() 和 hashCode()
- 带有用于匹配的 unapply() 方法的伴侣对象
但是将不可变数据结构定义为 case 类有什么缺点?
But what are the disadvantages of defining an immutable data structure as a case class?
它对班级或其客户有什么限制?
What restrictions does it place on the class or its clients?
在某些情况下,您应该更喜欢非 case 类吗?
Are there situations where you should prefer a non-case class?
推荐答案
一个很大的缺点:案例类不能扩展案例类.这就是限制.
One big disadvantage: a case classes can't extend a case class. That's the restriction.
您错过的其他优点,为了完整性而列出:兼容序列化/反序列化,无需使用new"关键字来创建.
Other advantages you missed, listed for completeness: compliant serialization/deserialization, no need to use "new" keyword to create.
对于具有可变状态、私有状态或无状态(例如,大多数单例组件)的对象,我更喜欢非大小写类.几乎所有其他内容的案例类.
I prefer non-case classes for objects with mutable state, private state, or no state (e.g. most singleton components). Case classes for pretty much everything else.
这篇关于声明 Scala 案例类有哪些缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!