https://kotlinlang.org logo
Title
c

coder82

11/04/2019, 11:31 AM
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

diesieben07

11/04/2019, 11:38 AM
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

coder82

11/04/2019, 11:39 AM
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

diesieben07

11/04/2019, 11:41 AM
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

coder82

11/04/2019, 11:44 AM
uhmm it looks like it wants to know the type
d

diesieben07

11/04/2019, 11:44 AM
Yes you need an unsafe cast to
SerializationStrategy<Any>
c

coder82

11/04/2019, 11:45 AM
it worked, jeez
how i was supposed to know it
😄
do you work a lot with serialization?
d

diesieben07

11/04/2019, 11:46 AM
No, never have 😄
well
i did once for a short experiment
c

coder82

11/04/2019, 11:46 AM
I asked myself, I get an Any but the type at runtime is known, why woudn't this work
d

diesieben07

11/04/2019, 11:46 AM
reified
is a compile-time thing
c

coder82

11/04/2019, 11:49 AM
that yes and actively using it successfully
but in this case T is not reified right? what do you mean?
d

diesieben07

11/04/2019, 11:50 AM
BinaryFormat.dump(obj: T)
has
T
reified. Since the compiler infers
Any
for
T
, it will use
Any::class
for the serializer lookup.
c

coder82

11/04/2019, 11:52 AM
ah ok but we are using the other dump overload function:
or was yours just an observation relating to what we wrote beforehand
d

diesieben07

11/04/2019, 11:52 AM
Yes, now we are.
c

coder82

11/04/2019, 11:52 AM
ok
d

diesieben07

11/04/2019, 11:52 AM
Yes
c

coder82

11/04/2019, 11:52 AM
hey how do u get the flag by your username?
do i need to set the status or something?
d

diesieben07

11/04/2019, 11:53 AM
Yes, thats my status message
c

coder82

11/04/2019, 11:53 AM
I see
perfect, proud Italians here
🎉 2
😉