Let me ask the question again in a different way. ...
# serialization
r
Let me ask the question again in a different way. Obviously its possible to retrieve a serializer if one knows the type e.g.:
Copy code
val stringToColorMapSerializer: KSerializer<Map<String, Color>> = serializer()
However, is it possible to retrieve a serializer generically? Since
class
definitions can't have reified
T
, the normal workaround is to pass in a
Class<T>
. If I know that
T
is an
@Serializable
can I get the
KSerializer<T>
from
Class<T>
?
e
there’s a
KClass<T>.serializer()
so yes
oh,
Class
, hm
r
Yeah unfortunately the underlying framework (Apache Beam) requires the Coder implementation to be serializable itself, meaning that its properties have to implement
<http://java.io|java.io>.Serializable
.
KClass
does not.
🤦 1
😮 1
Also, even if that weren't a constraint, as per my other thread,
KClass<T>.serializer()
is an internal API.
e
yeah you can just surpress that warning, i’m using that method in prod, works great
can’t help you on the Class/java.io.Serializable thing tho
good luck!
r
thx
Best workaround I've found so far is to create an abstract base class with most of the machinery, and have one concrete coder per serializable type. It works, but is annoying to have to be so repetitive.
r
@rnett That did work, thank you.
As a last follow-up I did find a way to do this without the internal API:
Copy code
serializer(clazz.kotlin.starProjectedType) as KSerializer<T>
but that introduces an unchecked cast. Still, I do believe that is better than using an internal API. I created https://github.com/Kotlin/kotlinx.serialization/issues/1228 as a feature request.