Inheritance by type restriction

Would it be possible for an interface to have access to properties/functions that will be available upon implementation.

Example.

interface Test<E> where E : Enum<E>, E : Test<E>

This interface would only be able to be implemented by an enum due to its type restrictions. However, you don’t get access to properties and functions of Enum.

Workaround

Currently you can just declare the properties/functions in your interface, and when you implement the interface, they will already be implemented by your class.

ex.

interface Test<E> where E : Enum<E>, E : Test<E> {

    val ordinal : Int

    fun output() {                    
        println("Ordinal is $ordinal")
    }                                 

}

enum class Things : Test<Things> {

    ORDINAL_1,
    ORDINAL_2

}

But honestly, that would be messy for something more complex. I’m not entirely sure if this is something you can already do, and it would be a great addition if possible.

1 Like

An issue with this that comes to mind is for with anonymous classes, would there also be a way to restrict the anon creation of these sort of interfaces?

Before 1.0, Kotlin actually had a feature like this. They referred to it as “Required Classes”. It was deprecated in M12, as the team cited it required significant “compiler magic” to support.

I believe the compiler has undergone a few refactors now, or at least it was recently undergoing a big one. Perhaps they may try to add in a similar feature in a future release.

2 Likes

Would it be possible to look into this? This is still something that would greatly be appreciated…

This would be awesome