Case objects vs Enumerations in Scala

前端 未结 14 1007
误落风尘
误落风尘 2020-11-22 16:45

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.

相关标签:
14条回答
  • 2020-11-22 17:34

    I've seen various versions of making a case class mimic an enumeration. Here is my version:

    trait CaseEnumValue {
        def name:String
    }
    
    trait CaseEnum {
        type V <: CaseEnumValue
        def values:List[V]
        def unapply(name:String):Option[String] = {
            if (values.exists(_.name == name)) Some(name) else None
        }
        def unapply(value:V):String = {
            return value.name
        }
        def apply(name:String):Option[V] = {
            values.find(_.name == name)
        }
    }
    

    Which allows you to construct case classes that look like the following:

    abstract class Currency(override name:String) extends CaseEnumValue {
    }
    
    object Currency extends CaseEnum {
        type V = Site
        case object EUR extends Currency("EUR")
        case object GBP extends Currency("GBP")
        var values = List(EUR, GBP)
    }
    

    Maybe someone could come up with a better trick than simply adding a each case class to the list like I did. This was all I could come up with at the time.

    0 讨论(0)
  • 2020-11-22 17:39

    The advantages of using case classes over Enumerations are:

    • When using sealed case classes, the Scala compiler can tell if the match is fully specified e.g. when all possible matches are espoused in the matching declaration. With enumerations, the Scala compiler cannot tell.
    • Case classes naturally supports more fields than a Value based Enumeration which supports a name and ID.

    The advantages of using Enumerations instead of case classes are:

    • Enumerations will generally be a bit less code to write.
    • Enumerations are a bit easier to understand for someone new to Scala since they are prevalent in other languages

    So in general, if you just need a list of simple constants by name, use enumerations. Otherwise, if you need something a bit more complex or want the extra safety of the compiler telling you if you have all matches specified, use case classes.

    0 讨论(0)
提交回复
热议问题