jeudi 23 janvier 2020

Scala Implementation of Reflection to find Member Name

If I have a case class situation like this:

case class ColorId(id: Int) 

With a companion object that looks like this:

/**
  * Contains all possible colors that can be applied.
  */
object ColorId {
  val RED = ColorId(1)
  val GREEN = ColorId(2)
  val BLUE = ColorId(3)
  val WHITE = ColorId(4)
  val BLACK = ColorId(5)
  val UNKNOWN = ColorId(6)
}

val blue = ColorId.BLUE

assert(blue.getNameString == "BLUE")

There is surely a way to use reflection to get the assert to be true. How should the implementation of the ColorId object's getNameString method look?

EDIT: There does not need to be a specific method. For example something like blue.getClass.getXXX.getName is acceptable.

EDIT #2: Removing this comparable part.





Aucun commentaire:

Enregistrer un commentaire