If I have a generated class A which uses a class B...
# ksp
z
If I have a generated class A which uses a class B, but I want to give the user the option to either write their own B or have B be created by my processor, is the correct way to do this to create a separate annotation which makes A's processor aware of this annotation over the class the user chooses as B, and if it is not present then generate?
y
not sure what triggers the generation of A but i would make it an explicit option there. e.g.
Copy code
annotation class GenerateA {
   val bClass: KClass? = null // if null, you generate
}
I'm not a super fan of "Detecting if B exists and if not generate" because that would be easy to create ambigious situation (like, how do you find B? if it is by class name, what if user had a typo etc)
1
z
I agree, I am just unsure of what other pattern I could use as an alternative option that is more type-safe and less error prone.
a
From my point of view it depends on, when you want the user to decide. Before you generate the class A & B or during runtime when the class A is used? I'd prefer to assign the instance of class B to A as late as possible. Therefore I'd provide B as a Constructor Parameter. Moreover I would always provide the generated class of B, so the user can implement whether he wants to instantiate A with generated B or a custom implementation of B.
Copy code
class A(private val bClass: B = Default generated()){ ... }
z
This generated class unfortunately needs to be generated early as it is responsible for some remote data source synchronization which I would like to load as soon as some valid credentials are found or input to the application.
a
Okay, then I think I do not understand your usecase in all details. KSP is able to generate your code before it gets compiled and is executed. When it is executed, an instance of class A is created. At the same moment your default instance of B (your generated code) is created or if the constructor of A receives a different impl. of B, that one is used. How does this affect your timing? And what do you mean with "remote data source synchronisation"?