Declare generic method returning enumeration

2019-08-13 11:00发布

问题:

I want to implement with Scala analog of the following java code:

static <T extends Enum> T getEnumByPrefix(String prefix, Class<T> enumClass) {
    for (T enumValue : enumClass.getEnumConstants()) {
        if (enumValue.name().startsWith(prefix)) {
            return enumValue;
        }
    }
    throw new NoSuchElementException();
}

But I can't figure how to declare method for scala.Enumeration.

I tried

def enumByPrefix[T <: Enumeration](prefix: String): T.Value = ...

but that doesn't compile.

I tried

def enumByPrefix[T <: Enumeration.Value](columnLabel: String): T = ...

but that doesn't compile too.

Basically I want to use it as follows:

object PaymentMethod extends Enumeration {
  val Insurance, Cash = Value
}
...
val paymentMethod: PaymentMethod.Value = enumByPrefix[PaymentMethod]("Insurance")

(I used byPrefix just for example, real algorithm will be different).

回答1:

scala> def enumByPrefix[T <: Enumeration](prefix: String, enum:T):Option[enum.Value] = 
              enum.values.find(_.toString.startsWith(prefix))

enumByPrefix: [T <: Enumeration](prefix: String, enum: T)Option[enum.Value]

Using it with WeekDay (defined here) :

scala> enumByPrefix("Mon",WeekDay)
res2: Option[WeekDay.Value] = Some(Mon)

scala> enumByPrefix("Mon",WeekDay).map(isWorkingDay)
res3: Option[Boolean] = Some(true)