# Generic constraint on Companion Object

**URL:** <https://discuss.kotlinlang.org/t/generic-constraint-on-companion-object/9408>\
**Category:** Uncategorized\
**Created:** [September 11, 2018, 11:02pm UTC](https://discuss.kotlinlang.org/t/generic-constraint-on-companion-object/9408 "2018-09-11T23:02:20Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![nullptr2this](https://avatars.discourse-cdn.com/v4/letter/n/b38774/32.png) [@nullptr2this](https://discuss.kotlinlang.org/u/nullptr2this)\
**Post date:** [September 11, 2018, 11:02pm UTC](https://discuss.kotlinlang.org/t/generic-constraint-on-companion-object/9408/1 "2018-09-11T23:02:20Z")

</div>

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`

---

<div class="post-metadata">

**Author:** ![roryaburks](https://avatars.discourse-cdn.com/v4/letter/r/67e7ee/32.png) [@roryaburks](https://discuss.kotlinlang.org/u/roryaburks)\
**Post date:** [September 12, 2018, 2:44pm UTC](https://discuss.kotlinlang.org/t/generic-constraint-on-companion-object/9408/2 "2018-09-12T14:44:31Z")

</div>

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:

```auto
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")
        }
    }
}

```

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [September 12, 2018, 2:58pm UTC](https://discuss.kotlinlang.org/t/generic-constraint-on-companion-object/9408/3 "2018-09-12T14:58:45Z")

</div>

Another option would be do declare an interface like this

```kotlin
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
}

```
