1

I have these two enums:

enum Season:
  case Warm, Cold

enum Territory:
  case Continente, Madeira, Açores

I want to create a method radioInputsFor which receives the enum type and a concrete enum value such that these invocations are valid:

radioInputsFor(Season, Season.Warm)
radioInputsFor(Season, Season.Cold)
radioInputsFor(Territory, Territory.Madeira)

And these invalid:

radioInputsFor(Season, Territory.Madeira)
radioInputsFor(Territory, Season.Cold)

I also want to invoke .values on the first parameter inside the method.

What are the correct generics and types I should use for the parameters?

This

def radioInputsFor[T <: Enum](default: T): T = default

Correctly restricts the first parameter to be an enum value. However I cannot find a suitable type that abstracts the enum type.

Edit: currently this is not possible. However this PR is adding the required functionality.

Simão Martins
  • 1,210
  • 11
  • 22
  • It appears that the companion of the enum type doesn't extend anything special. Out of curiosity, what is the use-case for accepting both an enum and a companion as parameters? That is, what would you do with `values`? – Michael Zajac Dec 11 '21 at 02:37
  • I want to create a radio input (in ScalaJS) for each case of the enum (using `values`), the second argument (a specific enum case) would be the radio input that would be checked by default. Receiving the enum type would also allow me to get its name. And I have 3 different unrelated enums for which I want to generate the radio inputs. – Simão Martins Dec 12 '21 at 13:51

1 Answers1

1

As already mentioned here, there currently seems to be no common interface for enum companion objects.

You can fall back to reflection:

import reflect.Selectable.reflectiveSelectable
def pointedEnum[E <: reflect.Enum](
  companion: { def values: Array[E] },
  value: E
): (List[E], E) =
  (companion.values.toList, value)

def demo() =
  pointedEnum(Season, Season.Warm)
  pointedEnum(Territory, Territory.Madeira)
  // pointedEnum(Season, Territory.Madeira) // Nope
  // pointedEnum(Territory, Season.Cold) // Nope
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93