I want to use code generation to solve a problem I...
# ksp
m
I want to use code generation to solve a problem I have, and while I hope that KSP will allow me to do what I want, I've been stumped by one aspect and I'm wondering if more experienced users know of a way to get around it or can suggest a better design. I want to supply a library containing the annotation and support classes, and a processor to do the generation based on the annotation. And I would like the user code to look something like the following:
Copy code
object HasAnnotatedProperty {
    @MyPropertyAnnotation("annotationParameter")
    val myProperty: MyLibraryType by MyLibraryDelegate
}
All the
My...
types here are supplied by the library and in particular the
MyLibraryDelegate
would then interact with the KSP-generated class to provide the library functionality. My problem is in how to let the library code for MyLibraryDelegate get a hold of the generated class instance. For a jvm target, this is easy as I could use jvm reflection and predictable class names to get to the class. But I want to do this for the full multiplatform ecosystem, with my own immediate use cases being Kotlin/Native, and there I don't see a way to go from a class name string to getting hold of an instance of the generated class. Is there a way to make this design work, or suggestions for an alternate design that works with the available tooling?
j
delegation is not modeled by KSP, is it possible to add the class literal of the delegation to the annotation value of your
myProperty
so that you can read the delegation from it?
m
I could add it to the annotation as well, but in my current design the Delegate is an object from my library, so that is already fully accessible. The intent is to use the same delegate object for all instances where the annotation is used, and use the parameters of the delegate call to distinguish the different property instances from each other. What is missing in the current design is a way to get a reference to the new class I write with KSP into my library code. Is there some way that adding the delegate object to the annotation parameters can help there?
j
Unfortunately currently it is not accessible, you might try some reflection hacks to access it if it is already in the classpath.
m
Yes, reflection will work on JVM, but I don’t know of any that will work on kmp/native projects. If you know of any such hacks for native, I’d happily investigate those. I was also looking for options to trigger an unreferenced class into doing something at startup of the app, but that hasn’t come to anything either.