6

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 Answer 1

7

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()
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for replying! It does compile when MyEnum is empty, but unfortunately does not when adding cases
I would have loved to avoid the valuesInternal() implementation but it does the job, thanks! :)
@lorenzo to a pity you can't make values to be override method and that's why it won't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.