I have a question regarding kotlinx serialization....
# server
g
I have a question regarding kotlinx serialization. I want to have a single superclass which has a function to print an object as JSON. The implementing classes can not have a body. Is there a way to get access to the subclass (or her members) from the superclass? Gist here to make it more clear what I want to do: https://gist.github.com/buijs-dev/f7d197bce7ab44578cf7bc1c568aa6a2 Ofcourse it does work by adding an abstract method to be implemented by the subclass, which returns a reference to said subclass. I however want to avoid having to add a body for this usecase.
h
I have done this with an abstract class.
getClass().getSimpleName()
worked fine in my case, so I guess
getClass()
is what you are looking for?
g
Maybe I misunderstand what you mean but it's not the class/name that is needed but the instantiated object itself. That's why returning 'this' from the implementing class works, because it's returns a reference to the actual object.
i
Explain please, why
this
doesn't work?
h
If there is no body in the implementing classes, why do you need more than their name?
g
Using 'this' in KlutterJSON<T> will reference KlutterJSON<T> but required is T.
The implementing classes have constructor params and I want to serialize those. See the class ExtensiveGreetingInfo here: https://github.com/buijs-dev/klutter/blob/main/test-project/kmp/common/src/commonMain/kotlin/dev/buijs/klutter/example/basic/backend/Greeting.kt
so if parent has an abstract method, for example "fun data(): T" and the child overrides it with "fun data() = this". then it works. But I don't want to do that because it violates the functional contract I made
My temporary solution for now is to write a single kt file before compilation which has an extension function for each response class
but Id prefer the interface way if it could work 🙂
h
Ah, the superclass is an interface? What if it is an abstract class? You could still implement everything in the abstract superclass, but only make it instantiable through the subclasses (that otherwise have no body). Would this solve the problem?
g
no it's an abstract class, see the gist: https://gist.github.com/buijs-dev/f7d197bce7ab44578cf7bc1c568aa6a2 🙂
what you are suggesting is what I am trying to do yes, that's the cleanest way because the implementing class has no boilerplate whatsoever