sagar.musale
sagar.musale

Reputation: 595

Is there any way to override the name of enum in scala?

I am new to the Scala. I am sorry if it's just basic one.

I want to have a way where I can Override the enum name using any method.

object ErrorCode extends Enumeration {

  type ErrorCode = Value
  
  val UnexpectedError = Value(1, "Unexpected Error")
  val ParamError = Value(2, "Param Error")

  val conflictingValues = Set(
    UnexpectedError
  )

  def get(id: Int): Option[ErrorCode.Value] =
    ErrorCode.values.find(x => x.id == id)

  // Some way to override
  def getErrorWithDifferentName(id: Int): Option[ErrorCode.Value] = {
  .... // some code which can return `Value(1, "Invalid Error")`
  }
}

I tried to create a Value at runtime in a enum function but didn't work.

  def getErrorWithDifferentName(id: Int): Option[ErrorCode.Value] = {
    if (conflictingValues.exists(x => x.id == id)) {
      Some(Value(id, getNameForConflictingError(id)))
    } else {
      get(id)
    }
  }

  private def getNameForConflictingError(id: Int): String = {
    "Invalid Error"
  }

Expectations

val err = ErrorCode(1).toString // Unexpected Error
val newErr = ErrorCode.getErrorWithDifferentName(1).toString // Invalid Error

Upvotes: 0

Views: 58

Answers (0)

Related Questions