案例对象与 Scala 中的枚举 [英] Case objects vs Enumerations in Scala
问题描述
是否有关于何时使用案例类的最佳实践指南(或 case 对象)与在 Scala 中扩展枚举?
Are there any best-practice guidelines on when to use case classes (or case objects) vs extending Enumeration in Scala?
它们似乎提供了一些相同的好处.
They seem to offer some of the same benefits.
推荐答案
一个很大的区别是 Enumeration
支持从一些 name
字符串实例化它们.例如:
One big difference is that Enumeration
s come with support for instantiating them from some name
String. For example:
object Currency extends Enumeration {
val GBP = Value("GBP")
val EUR = Value("EUR") //etc.
}
然后你可以这样做:
val ccy = Currency.withName("EUR")
当希望保留枚举(例如,保存到数据库)或从驻留在文件中的数据创建它们时,这很有用.然而,我发现一般来说,Scala 中的枚举有点笨拙,并且感觉像是一个笨拙的附加组件,所以我现在倾向于使用 case object
s.case 对象
比枚举更灵活:
This is useful when wishing to persist enumerations (for example, to a database) or create them from data residing in files. However, I find in general that enumerations are a bit clumsy in Scala and have the feel of an awkward add-on, so I now tend to use case object
s. A case object
is more flexible than an enum:
sealed trait Currency { def name: String }
case object EUR extends Currency { val name = "EUR" } //etc.
case class UnknownCurrency(name: String) extends Currency
所以现在我的优势是...
So now I have the advantage of...
trade.ccy match {
case EUR =>
case UnknownCurrency(code) =>
}
正如 @chaotic3quilibrium 指出的那样(为了便于阅读,做了一些更正):
As @chaotic3quilibrium pointed out (with some corrections to ease reading):
关于UnknownCurrency(code)"模式,还有其他方法来处理找不到货币代码字符串而不是打破".Currency
类型的闭集性质.UnknownCurrency
属于 Currency
类型现在可以潜入 API 的其他部分.
Regarding "UnknownCurrency(code)" pattern, there are other ways to handle not finding a currency code string than "breaking" the closed set nature of the
Currency
type.UnknownCurrency
being of typeCurrency
can now sneak into other parts of an API.
建议将该案例推送到 Enumeration
之外,并使客户端处理一个 Option[Currency]
类型,该类型将清楚地表明确实存在匹配问题和;鼓励"API 用户自己整理.
It's advisable to push that case outside Enumeration
and make the client deal with an Option[Currency]
type that would clearly indicate there is really a matching problem and "encourage" the user of the API to sort it out him/herself.
为了跟进这里的其他答案,case object
s 相对于 Enumeration
s 的主要缺点是:
To follow up on the other answers here, the main drawbacks of case object
s over Enumeration
s are:
无法遍历枚举"的所有实例.确实如此,但我发现在实践中很少需要这样做.
Can't iterate over all instances of the "enumeration". This is certainly the case, but I've found it extremely rare in practice that this is required.
无法从持久值轻松实例化.这也是正确的,但是,除了大量枚举(例如,所有货币)的情况外,这不会带来巨大的开销.
Can't instantiate easily from persisted value. This is also true but, except in the case of huge enumerations (for example, all currencies), this doesn't present a huge overhead.
这篇关于案例对象与 Scala 中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!