Search code examples
kotlingenerics

How to use "where" and extend another (generic) class at the same time in Kotlin?


I have two interfaces, Foo and Bar, and I have a class Baz<T : Foo>. I want to create a new class Buz<T> that extends Baz, where Buz's type parameter extends both Foo and Bar. So it'd look something like this:

interface Foo
interface Bar

open class Baz<T : Foo>
// doesn't work
class Buz<T> where T : Foo, T : Bar : Baz<T>()

what's the actual way of doing this in Kotlin?


Solution

    • The inheritance clause goes before the where ... type constraints.
    • You need to call the superclass constructor by adding () after Baz<T>.
    • Baz<T> must be open to allow other classes to inherit from it.

    So you should do:

    open class Baz<T : Foo>
    
    class Buz<T> : Baz<T>() where T : Foo, T : Bar