英文:
Restrict Generic Kotlin Enum to certain type
问题
我想在编译时强制参数的类型为实现接口的枚举:
```kotlin
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.CorrectEnum1) // 编译成功
myFunction(WrongTypeEnum.WrongEnum1) // 正确显示编译错误
问题是如果是一个泛型类,情况就不同:
class MyClass<T : Enum<out MyInterface>>
// 上述代码会显示以下编译时错误:
// 类型参数不在其边界内。
// 期望: Enum<out MyInterface>
// 找到: MyInterface
所以,问题是:我做错了什么,如何让 MyClass
能够接受也实现了 MyInterface
接口的枚举类?
英文:
I would like to enforce, at compile time, the type of a parameter to an Enum that also implements an interface:
interface MyInterface {
val value: String
}
enum class WrongTypeEnum {
WrongEnum1,
WrongEnum2,
}
enum class CorrectTypeEnum(override val value: String) : MyInterface {
CorrectEnum1("value1"),
CorrectEnum2("value2");
}
If I write a generic function, things work correctly:
fun <T : Enum<out MyInterface>> myFunction(param: T) {...}
myFunction(CorrectTypeEnum.TestEnum1) // compiles successfully
myFunction(WrongTypeEnum.WrongEnum1) // correctly shows compile error
Problem is that things don't work the same way if it's a generic class:
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
So, question is: what am I doing wrong and how can I make it that MyClass
can by typed to enum classes that also implement MyInterface
?
答案1
得分: 3
是的,类参数的语法稍微复杂一些:
class MyClass<T> where T: Enum<T>, T: MyInterface {}
同样的语法也适用于函数:
fun <T> myFunction(param: T) where T : Enum<T>, T: MyInterface {}
英文:
Yes, the syntax for class parameters is a little more convoluted:
class MyClass<T> where T: Enum<T>, T: MyInterface {}
The same syntax does also work for functions:
fun <T> myFunction(param: T) where T : Enum<T>, T: MyInterface {}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论