hey! I have an Interface MyInt and its implementat...
# getting-started
n
hey! I have an Interface MyInt and its implementation MyIntImp. I'm trying to define a custom annotation(\@MyAnnotation) which accepts one argument of type Class<MyInt>. When I'm trying to use the annotation like this \@MyAnnotation(MyIntImp::class it gives me an error that it expects Class<MyInt> and not Class<MyIntImp> what am i missing here?
j
Class<T>
is invariant in its type parameter, so by default
Class<MyIntImp>
is not a subtype of
Class<MyInt>
even if
MyIntImp
is a subtype of
MyInt
. You probably want
Class<out MyInt>
(with the
out
modifier) in your annotation declaration, not just
Class<MyInt>
. You can learn more about generics and variance here: https://kotlinlang.org/docs/generics.html
💡 1
n
opsy, right
10x buddy
kodee welcoming 1
hey again @Joffrey! will it work if MyInt is parameterzied? MyInt<T>
j
You will have the same problem transitively 🙂 Does
MyInt
have an
in
or
out
modifier on its own type parameter? Because that is what decides whether the subtyping relationship between
MyInt<T>
and
MyInt<U>
depends on the subtyping relationship between
T
and
U
.
Oh wait, but if we stick to the specific
Class<T>
example, you might have an issue.
Class<MyInt<A>>
doesn't really carry any meaning in itself, because the
Class
instance of a generic class/interface doesn't care about the type parameter.