Scala中的案例对象与枚举 [英] Case objects vs Enumerations in Scala

查看:97
本文介绍了Scala中的案例对象与枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于何时使用案例类(或案例对象)与扩展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.

推荐答案

一个很大的不同是,枚举附带了从某些名称实例化它们的支持。 c $ c>字符串。例如:

One big difference is that Enumerations 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.
} 

然后您可以执行以下操作:

Then you can do:

val ccy = Currency.withName("EUR")

在希望保留枚举时很有用(例如,到数据库)或从文件中的数据创建它们。但是,我发现总体上来说,枚举在Scala中有点笨拙,并且带有笨拙的附加组件的感觉,因此我现在倾向于使用 case对象 s。 案例对象比枚举更灵活:

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 objects. 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 type Currency 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.

要在此处跟进其他答案,案例对象超过枚举为:

To follow up on the other answers here, the main drawbacks of case objects over Enumerations are:


  1. 无法迭代枚举的所有实例。确实是这种情况,但是我发现在实践中这是非常罕见的。

  1. 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屋!

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