我希望在编译时将参数类型强制传递给也实现接口的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

推荐答案

是的,类参数的语法稍微复杂一些:

class MyClass<T> where T: Enum<T>, T: MyInterface {}

同样的语法也适用于函数:

fun <T> myFunction(param: T) where T : Enum<T>, T: MyInterface {}

Kotlin相关问答推荐

如何在Kotlin中为两个数据类创建可重用的方法?

在Kotlin中求n个ClosedRange实例相交的最常用方法是什么?

如何避免使用公共类实现内部接口

如何接受任何派生类KClass

正则表达式 FindAll 不打印结果 Kotlin

如何在 Kotlin 中使用具有继承的泛型

TestContainers PostgreSQLContainer 与 Kotlin 单元测试:Not enough information to infer type variable SELF

如何使用 Kotlin KClass 属性 simpleName 生成空值

参考 Kotlin 中的 Java 接口静态字段

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

如何从不同的功能发出流量值? Kotlin 协程

零安全的好处

如何使用 Coil 从 URL 获取位图?

Kotlin - 覆盖方法中的 IllegalArgumentException

当被Spring代理类访问时,Kotlin实例变量为null

使用 Kotlin 创建自定义 Dagger 2 范围

项目未与 Gradle 链接

Kotlin 警告:Conditional branch result of type ... is implicity cast of Any?

如何在 Gradle Kotlin DSL 中使用来自 gradle.properties 的插件版本?

为什么 Kotlin 会收到这样的 UndeclaredThrowableException 而不是 ParseException?