我应该更喜欢 Scala 中的密封类还是枚举?
我正在尝试为 Scala 实现 Plurk API 投标,但我需要做出设计选择。
例如,Plurk 用户的性别属性可以是“男”、“女”、“其他”之一。
sealed trait Gender
object Male extends Gender
object Female extends Gender
object Others extends Gender
问题是我是否应该像上面的代码示例那样更喜欢密封类/对象而不是枚举来表示枚举类型?
因为我发现我在使用其他Scala库时很少遇到枚举,并且很多Actor教程都使用密封类/对象来表示Actor的消息。
那么这是否意味着在 Scala 中,密封类是比枚举更好/传统的选择?
I'm trying to implement a Plurk API biding for Scala, but I have a design choice to made.
For example, the gender attribute of a Plurk user could be one of "male", "female", "other".
sealed trait Gender
object Male extends Gender
object Female extends Gender
object Others extends Gender
The question is should I prefer sealed class/object like above code example, over Enumeration to represent enumeration types?
Because I find that I rarely come across Enumeration when I use other Scala library, and lots of tutorial of Actor use sealed class/object to represent messages for Actor.
So does this means that in Scala, sealed class is a better/conventional choice over Enumeration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不需要迭代 Gender 对象或需要
next
和previous
等方法,那么类和对象是正确的解决方案。如果您需要“类和对象”和“scala.Enumeration”的功能 这个和您可能会对这个问题感兴趣。
If you don't need to iterate over your objects of Gender or need methods like
next
andprevious
, classes and objects is the right solution.If you need the features of the "classes and objects" and of "scala.Enumeration" this and this question could be of interest to you.
就类计数而言,使用
Enumeration
也便宜很多。在Gender
示例中,这并不重要,但如果您想通过具有 100 多个元素的枚举对处理器指令进行建模,它可能会开始变得重要。Using
Enumeration
is also quite a bit cheaper in terms of class count. In theGender
example that does not matter, but it might start to matter if you want to model processor instructions by an enumeration with 100+ elements.