Home > Enterprise >  Is there a way in Kotlin to ensure that a generic type that inherits a interface still is a interfac
Is there a way in Kotlin to ensure that a generic type that inherits a interface still is a interfac

Time:07-26

I wont to declare a function with a generic type which has to inherits from an other generic type that should be an interface and some other class. But Kotlin complains and don't wont to let me do this.

class SomeClass<T: SomeInterface> {

    fun <R>someFunktion(task: R) where  R : SomeOtherClass, R : T {}
}

If I just replace the generic type T in the function declaration with SomeInterface it works.

class SomeClass<T: SomeInterface> {

    fun <R>someFunktion(task: R) where  R : SomeOtherClass, R : SomeInterface {}
}

So it seems the problem is that Kotlin dose not know whether T is an interface or a class and if it would be a class it could not work because Kotlin dose not support multi inheritance for classes. So dose some one know a solution? Thank you already in advance for every effort.

CodePudding user response:

Writing your above code example results in the Kotlin compiler to complain:

Type parameter cannot have any other bounds if it's bounded by another type parameter

It says that you cannot have your variable R be bound by a second type parameter T. However, for whatever reason, the problem can just be suppressed: If you add the annotation

@Suppress("BOUNDS_NOT_ALLOWED_IF_BOUNDED_BY_TYPE_PARAMETER")
fun <R>someFunktion(task: R) where  R : SomeOtherClass, R : T {}

then Kotlin will stop complaining and everything works just fine.

  • Related