0

Assume you write a method with type-parameter. Assume the type parameter can be (but does not have to be) an enum type. Is there a way to infer the the companion object of the enum-type from inside the method-body.

Example:

enum MyEnum
   case A, B, C

def cleverMethod[T]: CoolAnswer = 
   // To return a cool answer, I'd love to analyze the type T and do something like:
   // If it is an enum-type then find the companion object and return it wrapped into 
   // an instance of CoolAnswer. Or use the companion object to find all elements
   // elements of the enum.
   ???

// Use the method with MyEnum as parameter
val test = cleverMethod[MyEnum]
// And the instance test receives now wraps the companion object.

Suggestion to the scala developers: If there is no easy way to do this yet, why not provide one in the next stage of evolution of scala? The idea might be to make the companion-object of an enumeration accessible from its type. Thanks!

StepM
  • 1
  • 1
  • 2
    Does this answer your question? [How to create a general method for Scala 3 enums](https://stackoverflow.com/questions/69743692/how-to-create-a-general-method-for-scala-3-enums) – Gaël J May 15 '22 at 09:58

1 Answers1

0

I have just found this post:

How to create a general method for Scala 3 enums

This is a good answer at the price of having to extend each enum type from the Java-Enum-class. No big deal, but imagine that I wish to make my method "cleverMethod" available through a library. I would have to explain to every user that she needs to implement enums in this particular way to make things work. Can this be avoided?

StepM
  • 1
  • 1