Generic constraint on Companion Object


#1

Is it possible to constraint a generic type based on it 1) having a companion object and 2) that companion object implementing a given interface?

Something like:

class SomeClass<T> where T.Companion : SomeInterface


#2

As far as I’m aware of, there exists no direct way to do this, but you could always have the class implement the interface itself by delegating it to its companion object:

fun <T : IThingDoer> multiDo(t: T)
{
    repeat(10) {t.doThing()}
}

interface IThingDoer
{
    fun doThing()
}

class Something : IThingDoer by Companion
{
    companion object : IThingDoer {
        override fun doThing() {
            println("thing done")
        }
    }
}

#3

Another option would be do declare an interface like this

interface Contains<T> {
    val contained: T
}

class Something: Contains<Foo>{
   override val contained get() = Companion // not sure what the syntax here is
   companion object: Foo
}