我希望在编译时将参数类型强制传递给也实现接口的Enum:
interface MyInterface {
val value: String
}
enum class WrongTypeEnum {
WrongEnum1,
WrongEnum2,
}
enum class CorrectTypeEnum(override val value: String) : MyInterface {
CorrectEnum1("value1"),
CorrectEnum2("value2");
}
如果我编写一个泛型函数,一切都会正常工作:
fun <T : Enum<out MyInterface>> myFunction(param: T) {...}
myFunction(CorrectTypeEnum.TestEnum1) // compiles successfully
myFunction(WrongTypeEnum.WrongEnum1) // correctly shows compile error
问题是,如果它是泛型类,事情就不会以相同的方式工作:
class MyClass<T : Enum<out MyInterface>>
// The above line shows the following compile time error:
// Type argument is not within its bounds.
// Expected: Enum<out MyInterface>
// Found: MyInterface
因此,问题是:我做错了什么,我如何才能通过将MyClass
类型化为也实现MyInterface
的枚举类来实现MyClass
?