https://kotlinlang.org logo
#ksp
Title
# ksp
j

jean

03/03/2023, 10:33 AM
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

jean

03/03/2023, 1:37 PM
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

glureau

03/03/2023, 1:45 PM
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

jean

03/03/2023, 1:56 PM
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

Jiaxiang

03/03/2023, 9:55 PM
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

jean

03/04/2023, 9:34 AM
Thanks for the help!
82 Views