Search code examples
scalaenumsscala-3

How to create a general method for Scala 3 enums


I want to have a simple enumDescr function for any Scala 3 enum.

Example:

  @description(enumDescr(InvoiceCategory))
  enum InvoiceCategory:
    case `Travel Expenses`
    case Misc
    case `Software License Costs`

In Scala 2 this is simple (Enumeration):

def enumDescr(enum: Enumeration): String =
  s"$enum: ${enum.values.mkString(", ")}"

But how is it done in Scala 3:

def enumDescr(enumeration: ??) = ...

Solution

  • I don't see any common trait shared by all enum companion objects.

    You still can invoke the values reflectively, though:

    import reflect.Selectable.reflectiveSelectable
    
    def descrEnum(e: { def values: Array[?] }) = e.values.mkString(",")
    
    enum Foo:
      case Bar
      case Baz
    
    descrEnum(Foo) // "Bar,Baz"