0

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
3
  • 1
    Don't ever use Enumeration is broken in multiple ways. Take a look to the Enumeratum library, or enum in Scala 3 or just using your own sealed trait + case objects Commented Oct 10, 2023 at 15:09
  • Could you please explain a bit about approach using sealed trait + case objects? Commented Oct 10, 2023 at 16:27
  • 1
    You just define everything manually :scastie.scala-lang.org/BalmungSan/9K9QbUOCQfKEYWvCpzPCOQ Commented Oct 10, 2023 at 16:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.