Interface extension and type generics gives "Type argument is not within its bounds"

Viewed 29
interface A<T> {
    fun get(): T
}
abstract class C<T: A<K>, K: Any>

class AImpl : A<AImpl> {
    override fun get() = this
}
class CImplA : C<AImpl, AImpl>()

In the snippet above, I created:

  • a simple interface A that provides a function to convert the implementing class to another type; and
  • an abstract class C that accepts both A and its type parameter as type parameters.

and two implementations:

  • an implementation of the interface A that returns the same object; and
  • an implementation of the abstract class C that correctly accepts AImpl as both type parameters.

Note: The first interface and the abstract class can be considered part of a library, and cannot be modified.

My goal is to prevent the explicit override of the get() function for each class X that implements A<X>. To achieve this I tried creating another interface:

interface B : A<B> {
    override fun get() = this
}

but the compiler complains when I try to use this interface:

class BImpl : B
class CImplB : C<BImpl, BImpl>()
//               ^^^^^ -> Type argument is not within its bounds.
//                        Expected: A<BImpl>
//                        Found: BImpl

Is this a compiler limitation, is it due to type erasure in some way or am I doing something wrong?

0 Answers
Related