Kotlin define interface for enum class values method

匆匆过客 提交于 2019-12-11 18:25:47

问题


if I define an enum class, let's say:

enum class MyEnum { }

I can do the following as enum class all have a values method:

val values = MyEnum.values()

Now I want my enum to implement an interface and have access to the values() method:

enum class MyEnum : EnumInterface { }

interface EnumInterface {
    fun values() : Array<T>

    fun doStuff() {
        this.values()
    }

}

This doesn't compile and I'm sure how to type the values method. Is it possible to define such interface? Thanks!


回答1:


You were really close to correct answer. You need to define generic interface and you enum should extend it typed with enum's class like this:

enum class MyEnum : EnumInterface<MyEnum> {
    A,B,C;
    override fun valuesInternal() = MyEnum.values()
}

interface EnumInterface<T> {    
    fun valuesInternal():Array<T>

    fun doStuff() {
        this.valuesInternal()
    }
}


来源:https://stackoverflow.com/questions/56126945/kotlin-define-interface-for-enum-class-values-method

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