cer*_*hif 1 generics enums kotlin companion-object
我想做如下的事情:
inline fun<T: Enum<T>> myFunction(enumStr: String){
T.valueOf(enumStr)
//...
}
Run Code Online (Sandbox Code Playgroud)
这样我的泛型参数就被限制为枚举类类型,以便我可以访问 valueOf 函数。我收到一条错误消息,指出:
Type parameter 'T' cannot have or inherit a companion object, so it cannot be on the left hand side of dot
我理解这意味着我不能在泛型上使用伴随对象函数。有什么方法可以实现我想要的 - 将字符串转换为通用枚举?
如果您具体化类型参数,则可以使用该enumValueOf函数(此处为 doc)。像这样:
inline fun <reified T: Enum<T>> myFunction(enumStr: String) {
val enumValue = enumValueOf<T>(enumStr)
//...
}
Run Code Online (Sandbox Code Playgroud)