Thread
#serialization
    r

    rocketraman

    1 year ago
    Let me ask the question again in a different way. Obviously its possible to retrieve a serializer if one knows the type e.g.:
    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

    edenman

    1 year ago
    there’s a
    KClass<T>.serializer()
    so yes
    oh,
    Class
    , hm
    r

    rocketraman

    1 year ago
    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.
    Also, even if that weren't a constraint, as per my other thread,
    KClass<T>.serializer()
    is an internal API.
    e

    edenman

    1 year ago
    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

    rocketraman

    1 year ago
    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.
    rnett

    rnett

    1 year ago
    r

    rocketraman

    1 year ago
    @rnett That did work, thank you.
    As a last follow-up I did find a way to do this without the internal API:
    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.