kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Symmetry in serializer API lookup

Open swankjesse opened this issue 2 years ago • 4 comments

Kotlin serialization already has these APIs

  • SerializersModule.getContextual(KClass<T>, List<KSerializer<*>>)
  • SerializersModule.serializer(KType)

I’d like this API:

  • SerializersModule.serializer(KClass<T>, List<KSerializer<*>>)

In particular I have a root type (like LinkedHashSet or Pair or Map.Entry) and serializers for the parameter types, and I want a serializer for the composed type.

swankjesse avatar Aug 31 '22 03:08 swankjesse

I recall we had a similar SerializersModule extension in mind, AFAIR it also requires an extension on the registration phase.

qwwdfsad avatar Sep 05 '22 12:09 qwwdfsad

I think it should be easy to add such a function. Can you tell a bit more about use-case?

sandwwraith avatar Sep 06 '22 16:09 sandwwraith

My use case is a bit exotic. I’m doing method binding (not unlike Retrofit) and I want to look up serializers for interface parameters and response types. For the most part this just works and is wonderful.

But I also wanna do parameterized types properly. For example, I might be given this:

interface PagerService<T> {
  fun nextPage(): List<T>
  fun tableOfContents(): Map<String, T>
}

In this example I’ll have a KSerializer<T> and will want to look up a KSerializer<List<T>> and a KSerializer<Map<String, T>>.

I don’t actually have enough information to build a KType for List<T> because I don’t know T; only its serializer.

More details on the project are here! https://github.com/cashapp/zipline/

swankjesse avatar Sep 06 '22 18:09 swankjesse

Note you can do this manually, e.g.

when(thisClass) {
 is List::class -> ListSerializer(myArgsSerializer[0])
  is Map::class -> // etc....
}

But in general case, yes, such function is required

sandwwraith avatar Sep 07 '22 12:09 sandwwraith

Worth taking it into account along with serializer(Type) stabilization for retrofit

qwwdfsad avatar Oct 10 '22 12:10 qwwdfsad