I want to Cbor.dump a class and I need to pass Tes...
# ktor
c
I want to Cbor.dump a class and I need to pass TestClass.serializer(), but the type I receive is Any, is there a way to get that TestClass.serializer() at runtime without testing the type with when/is? But it looks like to me there is no way to do that as .dump requires the <T> at compile time
Here is my snippet in case you want to see what I am trying to do:
d
There is an extension function
dump(obj: T)
on
BinaryFormat
that uses reflection to find the serializer.
So you can just do
Cbor.dump(value)
c
if I do that I get an exception
let me check which one
kotlinx.serialization.SerializationException: Can't locate argument-less serializer for class kotlin.Any. For generic classes, such as lists, please provide serializer explicitly.
I suspect that since it's any..
I suspect that since it's "Any", it can't figure it out
d
Ah, yeah, you need the actual class... You can maybe use
context.getContextualOrDefault(value::class)
as the serializer
That will use the class that
value
has at runtime.
c
image.png
uhmm it looks like it wants to know the type
d
Yes you need an unsafe cast to
SerializationStrategy<Any>
c
it worked, jeez
how i was supposed to know it
😄
do you work a lot with serialization?
d
No, never have 😄
well
i did once for a short experiment
c
I asked myself, I get an Any but the type at runtime is known, why woudn't this work
d
reified
is a compile-time thing
c
that yes and actively using it successfully
but in this case T is not reified right? what do you mean?
d
BinaryFormat.dump(obj: T)
has
T
reified. Since the compiler infers
Any
for
T
, it will use
Any::class
for the serializer lookup.
c
ah ok but we are using the other dump overload function:
or was yours just an observation relating to what we wrote beforehand
d
Yes, now we are.
c
ok
d
Yes
c
hey how do u get the flag by your username?
do i need to set the status or something?
d
Yes, thats my status message
c
I see
perfect, proud Italians here
🎉 2
😉