Case objects vs Enumerations in Scala

前端 未结 14 1166
误落风尘
误落风尘 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: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.

提交回复
热议问题