Hey everyone, I have kind of a weird thing with ge...
# getting-started
s
Hey everyone, I have kind of a weird thing with generics. I have an
abstract class A<X,Y,Z: A<X,Y,Z>>
which I am subclassing to
class CompositeA<X,Y>: A<X,Y,CompositeA<X,Y>>
Now,
A
has an
abstract fun copy(): Z
and
CompositeA
has a property
components: List<A<X,Y,*>>
. When I try to iterate through objects from
components
, call
copy()
on them,and put the put the results into a
List<A<X,Y,*>>
the IDE gives me an error saying I'm trying to put something of type of type
A<*,*,*>
into the List, which is incompatible. I can cast the result of
copy()
by using
as A<X,Y,*>
, but then I get an unchecked cast warning. Any ideas what I'm not seeing here?
h
I'm a bit too tired to fully figure out your class relations here, but I'm guessing you're running into an issue with erased types. You'd need to use an inline function and reify the types to check them. However, if you're certain the function can never be used without correct type parameters, just do your cast and ignore the warning
s
It is a confusing set of generics, basically Z is used so abstract methods return objects of the subclass type so implementations can take advantage of subclass-specific methods without having to cast. I think I figured out the problem, but not a better workaround than casting the objects. Wildcarding Z erases it's generics, even though its first two generics must match X and Y.