Case objects vs Enumerations in Scala

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

    Update March 2017: as commented by Anthony Accioly, the scala.Enumeration/enum PR has been closed.

    Dotty (next generation compiler for Scala) will take the lead, though dotty issue 1970 and Martin Odersky's PR 1958.


    Note: there is now (August 2016, 6+ years later) a proposal to remove scala.Enumeration: PR 5352

    Deprecate scala.Enumeration, add @enum annotation

    The syntax

    @enum
     class Toggle {
      ON
      OFF
     }
    

    is a possible implementation example, intention is to also support ADTs that conform to certain restrictions (no nesting, recursion or varying constructor parameters), e. g.:

    @enum
    sealed trait Toggle
    case object ON  extends Toggle
    case object OFF extends Toggle
    

    Deprecates the unmitigated disaster that is scala.Enumeration.

    Advantages of @enum over scala.Enumeration:

    • Actually works
    • Java interop
    • No erasure issues
    • No confusing mini-DSL to learn when defining enumerations

    Disadvantages: None.

    This addresses the issue of not being able to have one codebase that supports Scala-JVM, Scala.js and Scala-Native (Java source code not supported on Scala.js/Scala-Native, Scala source code not able to define enums that are accepted by existing APIs on Scala-JVM).

提交回复
热议问题