'How to determine if a functions return type is a primitive in ksp
Short version: How can I tell if a KSType
is a primitive or even compare it to a kotlin type?
I'm writing a code generator in Kotlin using ksp. I am iterating through a type's functions and have a KSFunctionDeclaration
. I want to know if the return type of the function is a primitive.
I can see the name of the type using it.returnType?.resolve()?.declaration?.simpleName
and that will show Long
or Int
etc. So I can just check if that name == "Long"
etc. But it seems like there should be a way to compare to an actual type.
I found the builtins
property on Resolver
that has a property of type KSType
for each built in type. But I don't know how to get to the Resolver
.
Solution 1:[1]
builtIns
are the way to compare types and return types when it comes to primitives.
Resolver
can be passed as argument to your visitors, it's totally safe.
class ConnectFunctionVisitor(
private val environment: MySymbolProcessorEnvironment,
private val resolver: Resolver
) : KSDefaultVisitor<KSFunctionDeclaration, FunSpec>()
For non-primitive types you can use this extension:
inline fun <reified T> KSType.isAssignableFrom(resolver: Resolver): Boolean {
val classDeclaration = requireNotNull(resolver.getClassDeclarationByName<T>()) {
"Unable to resolve ${KSClassDeclaration::class.simpleName} for type ${T::class.simpleName}"
}
return isAssignableFrom(classDeclaration.asStarProjectedType())
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nikola Despotoski |