https://kotlinlang.org logo
Title
f

Fabio

02/16/2021, 10:20 PM
How would I get the class of a KSPropertyDeclaration? I can see
it.type.resolve()
is a
KSType
, and I see
isAssignableFrom(KSType)
but still not sure how to compare it to a
KClass
like
Module::class.java
y

yigit

02/16/2021, 10:20 PM
you need to get the type from the KSClass
you can use asStarProjectedType
j

Jiaxiang

02/16/2021, 10:33 PM
Also
KSType.declaration
will direct you to the
KSClass
of that type. However it is recommended to use
KSType
for comparing to handle subtypee, i.e. use the approach above.
f

Fabio

02/16/2021, 10:33 PM
but how do I get the KSClass from both KSType on one object and KClass on the other object?
y

yigit

02/16/2021, 10:34 PM
what is
object
?
oh
you can use
Resolver.getClassDeclarationByName("qalified name of Module")
and then get type from it as
asStarProjectedType
🙌 1
if you want to find the class of a type, then you can use its declaration but as @Jiaxiang mentioned, it is best to use types for type checking unless you have a case where you don't want to accept subtypes etc
f

Fabio

02/17/2021, 7:48 AM
I made my code work but not sure if this is a code smell:
val moduleKsType =
            org.koin.core.module.Module::class.java
                .let {
                    object : KSName {
                        override fun asString(): String = it.canonicalName
                        override fun getQualifier(): String = "Not important "
                        override fun getShortName(): String = it.simpleName
                    }
                }
                .let {
                    resolver.getClassDeclarationByName(it)
                        ?.asStarProjectedType()
                }
and then to check for the type of a given
val d: KSPropertyDeclaration
I'm doing
d.type.resolve().declaration == moduleKsType?.declaration
(which in a non-ksp project would be equivalent of using the
is
keyword, as in
obj is org.koin.core.module.Module
)
j

Jiaxiang

02/17/2021, 7:38 PM
you can simply use
resolver.getClassDeclarationByName(name: String)
function which will accept a string for name so you don’t have to create that long statement for creating a dummy
KSName
object.
Alternatively, if you prefer using reflection, there is also a function
fun <reified T> Resolver.getClassDeclarationByName()
which will help.
y

yigit

02/17/2021, 7:55 PM
It wouldn't be equal to is check because is check would accept subclasses but i guess you don't have subclasses here
f

Fabio

02/17/2021, 10:13 PM
at this moment I'm not worried with subclasses, probably much later after the POC is ready