Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading