Kotlin define interface for enum class values meth

2019-08-21 03:45发布

问题:

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()
    }
}