maxmello
02/18/2020, 4:25 PMabstract class A<T : A<T>>(
val id: Id<T>
)
class B(id: Id<B>) : A<B>(id)
class C(id: Id<C>) : A<C>(id)
I want to have polymorphism in a DB model, and the library provides type safe Id
with generics. I want the superclass to have the id property and to restrict it to be of any subclass of itself. For this I have the A<T : A<T>>
definition on top. Now, a subclass passes in its own type and only allows id to be of that type, making sure I never have Id<C>
in a B
class.
But when trying to use that type system, I have the problem of recursive definition of the parameter of A. For example when mapping a list of instances of objects holding subclasses of A, I need to specify the type variable like this:
SomeClassHoldingASubclasses(…)
=> SomeClassHoldingASubclasses<A<A<A ... > > >
It is not possible to do it like this: SomeClassHoldingASubclasses<*>
“projections are not allowed on type arguments of functions and properties”
If I remove the type variable from A, I cannot pass an id : Id<B> to the constructor of A.
I’m trying to get this to work for quite some time now, but are these polymorphic / self-referencing type variables even possible? Should I use in
or out
(I tried but that also went weird fast)?Andrzej
02/18/2020, 5:03 PMSomeClassHoldingASubclasses
, where this problem occurs?Dennis
02/18/2020, 5:08 PMarrayOf<...>()
The question is why do you want to keep these objects in the same list? Aren't they different? Do you get any benefit from having a common parent class?maxmello
02/18/2020, 5:14 PMmaxmello
02/18/2020, 5:17 PMDennis
02/18/2020, 5:19 PM