Declare generic method returning enumeration

余生颓废 提交于 2020-01-05 05:19:54

问题


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)


来源:https://stackoverflow.com/questions/21511656/declare-generic-method-returning-enumeration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!