Case objects vs Enumerations in Scala

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

    For those still looking how to get GatesDa's answer to work: You can just reference the case object after declaring it to instantiate it:

    trait Enum[A] {
      trait Value { self: A =>
        _values :+= this
      }
      private var _values = List.empty[A]
      def values = _values
    }
    
    sealed trait Currency extends Currency.Value
    object Currency extends Enum[Currency] {
      case object EUR extends Currency; 
      EUR //THIS IS ONLY CHANGE
      case object GBP extends Currency; GBP //Inline looks better
    }
    

提交回复
热议问题