lloydmeta / enumeratum

A type-safe, reflection-free, powerful enumeration implementation for Scala with exhaustive pattern match warnings and helpful integrations.
MIT License
1.18k stars 146 forks source link

Override a single entry with custom name #389

Closed jpanda109 closed 4 months ago

jpanda109 commented 4 months ago

Is it possible to override the value of a singular entry with a custom name? Something like:

import enumeratum._
import enumeratum.EnumEntry._

sealed trait Greeting extends EnumEntry with Snakecase

object Greeting extends Enum[Greeting] {

  val values = findValues

  case object Hello        extends Greeting
  case object GoodBye      extends Greeting
  case object ShoutGoodBye extends Greeting with EntryName("foo")

}
lloydmeta commented 4 months ago

Does this help https://github.com/lloydmeta/enumeratum?tab=readme-ov-file#manual-override-of-name ?

An example of that is here (this shows multi-name usage but you don't have to do that)

https://github.com/lloydmeta/enumeratum/blob/75fffbbcac3a0166fe92c3b75d4eb586d353ba66/enumeratum-core/src/test/scala/enumeratum/Models.scala#L264-L277

jpanda109 commented 4 months ago

Not quite - I was hoping for something where I can only rename a single case, and have the others use the default of whatever mixing i've already set.

So in the case above, it'd be something like:

import enumeratum._
import enumeratum.EnumEntry._

sealed trait Greeting extends EnumEntry with Snakecase

object Greeting extends Enum[Greeting] {

  val values = findValues

  case object Hello        extends Greeting
  case object GoodBye      extends Greeting
  // not valid scala
  case object ShoutGoodBye extends Greeting with EntryName("foo")
}

Greeting.withName("hello") == Hello
Greeting.withName("good_bye") == GoodBye
Greeting.withName("foo") == ShoutGoodBye
lloydmeta commented 4 months ago

The issues in this repo are not meant to walk people through exact solutions to Scala code problems. The key in the section I linked to in my reply was

manually override the def entryName: String method.

Not an exact copy pasta of the code 😅 . Anyways, you should consider something like the following

import enumeratum._
import enumeratum.EnumEntry._

sealed trait Greeting extends EnumEntry with Snakecase

object Greeting extends Enum[Greeting] {

  val values = findValues

  case object Hello        extends Greeting
  case object GoodBye      extends Greeting
  case object ShoutGoodBye extends Greeting {
    override val entryName: String = "foo"
  }

}

If you want, you can declare an intermediate trait/abstract class to make the entryName overriding more convenient for the Greetings that you want to have non-default names.

jpanda109 commented 4 months ago

Ahh sorry, I misread, and sorry for clogging the issues - I didn’t see a link to any other discussion forums in the readme. Out of curiosity, is there a better place for questions?

I’ll go ahead and close this out - thank for the help.