Is it possible with KSP to generate a companion ob...
# ksp
j
Is it possible with KSP to generate a companion object for an already existing class (declared by the user)? I need to add a “static” extension function to classes I do not own, however they might not have a companion object since this is not in my control.
🚫 2
n
No, you need a compiler plugin to do if you compile the sources, otherwise the "user" have to add it.
a
no, unfortunately you need the user to add
companion object
themself
we have the same problem in Arrow Optics…
r
Just to clarify... this would work correct?
Copy code
class Potato {
    companion object
}

// Generate w/ KSP
fun Potato.Companion.b() = 2

fun main() {
    println(Potato.b())
}
It's not the cleanest, since the user needs to write the words "companion object", and comes w/ the limitations of extension functions, but maybe can hack together the functionality you need?
j
@Norbi thank you for the clarification, voted 🙂
@Ryan Brink yes, this is something I had in mind, I might require my users to do this. It’s not the best but at least it works.
a
Not sure if it applies in your case, but you can require an annotation triggering codegen to be applied to the companion object, which therefore guarantees that it is declared and you can add extensions to it
j
Oh! This applies to me, I should have mentioned I will require users to add an annotation. How does the codegen work?
n
How does the codegen work?
This is the case when you need a compiler plugin 🙂 (Because KSP can generate only new classes and resource, modifying an existing class is possible only by using compiler plugins.)
An easy (but a little bit uncomfortable) KSP-based workaround: only validate the annotated classes using the KSP plugin, and simply issue a compilation error if the annotated class does not have a companion object.
108 Views