I'm wondering how to check generic type parameters...
# ksp
d
I'm wondering how to check generic type parameters for a specific subclass of a generic parent type. Will put an example in the 🧵
(The example is made up but should get the point across)
Copy code
// Case 1
abstract class Converter<I, O>
class NumericStringToNumberConverter : Converter<String, Int>

// Case 2
abstract class Converter<I, O>
abstract class ToStringConverter<I> : Converter<I, String>
abstract class DoubleToStringConverter : ToStringConverter<Double>
For case 1, when I visit a "NumericStringToNumberConverter" KSClassDeclaration, I want to know that it implements "Converter" and that its type parameters are bound to String and Int. For case 2, when I visit a "DoubleToStringConverter", I want to know that it implements "Converter" as well, and that its type parameters are bound to Double and String.
I assume what I need to do is, for each class, resolve the super types, and then keep visiting up the chain until I find a class with qualified name
whatever.the.path.is.to.Converter
(*) but then I'm not sure how to check what its specific type parameters are. (*) Side note: Should I just do a string check against the fully qualified name? Or should I somehow fetch the KSType of
whatever.the.path.is.to.Converter
earlier and check against that?
d
I think you got the right idea with walking the super types. Taking the
KSClassDeclaration
for`NumericStringToNumberConverter` you can find out the type arguments like this:
val converterTypeArguments = declaration.getAllSuperTypes().firstOrNull *{* it.declaration.qualifiedName.asString() == "Converter" *}*?.arguments
then:
_assert_(converterTypeArguments?.map { it.type.resolve() } == _listOf_(resolver.builtIns.stringType, resolver.builtIns.intType))
d
Thanks! I'll give that a shot.
Also, apologies if a basic question, but given a fully qualified class name, can I easily ask KSP to get a KSType for it (or null if not found)? Or is the way to do this by doing a first round
visit
pass with a visitor whose purpose is to fetch the
KSType
, and then pass that into a second round visitor?
(Or maybe I'm just overthinking it and should do a string test against
it.resolve().declaration.qualifiedName.asString()
)
d
given a fully qualified class name, can I easily ask KSP to get a KSType for it (or null if not found)?
Would
resolver.getClassDeclarationByName()
work for that? Once you have the
KSClassDeclaration
you can easily get to its
KSType
.
d
Ah, I thought I searched resolver, don't know why I didn't see that. I was tired..... thanks!
@David Rawson This worked perfectly, thank you!
🚀 1