Search code examples
scalasprayspray-json

Why is Value String not a stable identifier even when defined as a val


object HydraTable extends Enumeration {
  val UserTable, MpesaTable, ChequeTable, PaypalTable = Value
}

matchTable.tableType match {

  case HydraTable.UserTable.toString =>
    // do somet
  case HydraTable.MpesaTable.toString => 
    // do somet
    // returns error below

This returns an error on case -> HydraQueueWorker.scala:58: stable identifier required, but HydraTable.MpesaTable.toString found.

Are the values not stable identifiers?


Solution

  • The toString is a method and its invocation can yield a different value each time : you can easily create a case class and override the toString to return the string value of a random integer

    If you look at the toString definition you see it's a method (and a non final one)

    @SerialVersionUID(8476000850333817230L)
    abstract class Enumeration (initial: Int) extends Serializable {
      thisenum =>
    
     def this() = this(0)
    
      /* Note that `readResolve` cannot be private, since otherwise
         the JVM does not invoke it when deserializing subclasses. */
      protected def readResolve(): AnyRef = thisenum.getClass.getField(MODULE_INSTANCE_NAME).get(null)
    
      /** The name of this enumeration.
       */
      override def toString =
        ((getClass.getName stripSuffix MODULE_SUFFIX_STRING split '.').last split
           Regex.quote(NAME_JOIN_STRING)).last
    

    So you can create your enumeration, override it and return a random value.