Is it possible to get the value of a property with...
# ksp
j
Is it possible to get the value of a property with KSP?
Copy code
@MyAnnotation
class MyConfig : Config {
    override val configField1: String = "a"
    override val configField2: String = "b"
}
Is it possible to get “a” out of ksClassDeclaration?
🚫 3
j
If i turn my code to this :
Copy code
@Config
fun myConfig() = ConfigData(
    configField1 = String = "a"
    configField2 = String = "b"
)
Is there a way to execute that function to get a hold on
ConfigData
? I tried this
(this as () -> ConfigData).invoke()
but it gave me
com.google.devtools.ksp.symbol.impl.kotlin.KSFunctionDeclarationImpl cannot be cast to kotlin.jvm.functions.Function0
. I know I can get values from annotation arguments but I find it pretty ugly to have code such as this :
Copy code
@Config(
    configField1 = String = "a"
    configField2 = String = "b"
)
object MyConfig
I don’t think it scales very well
g
You can't execute target code during the processing phase (or else it will be a chicken and egg problem). KSFunctionDeclarationImpl is a representation of the structure of the function, it's not the function and does not hold a reference to the function pointer (afaik).
Maybe if you can generalize the problem we can offer some other solutions than the annotation parameter (I think it's unlikely but without more context I can't tell).
j
I’m just trying to generate a bunch of boiler code based on some configuration values. Maybe KSP isn’t the best for that. Or I need to put the config values in the annotation
j
Your best option is to put it in the annotation. Casting as KFunction will never work because it is at compile time no reflection information is available, you can also try to write a custom compiler plugin but the complexity around evaluating expression can go unexpected, i.e. won’t scale well either.
j
Thanks for the help!
112 Views