Is there any way to declare that a parameter to a ...
# serialization
e
Is there any way to declare that a parameter to a function needs to be a type that is Serializable? For example:
Copy code
fun persist(foo: ???) {
  Json.encodeToString(foo)
}
e
not that i know of. afaik it’s not knowable at compile time which is what you’re after
j
Require the caller to supply a KSerializer
⬆️ 2
e
yeah, you still don’t know if that serializer is real until runtime tho
you can call KClass.serializer() on whatever class you want
e
KClass.serializer
is marked as
InternalSerializationApi
. Is there any other way to get a KSerializer?
Oh I see there's one generated for each @Serializable type
☝️ 2
e
forgot i was using the internal one. Jake is right,
Foo.serializer()
is probably your best bet
j
Isn't it typed? So it would be
fun <T> persist(foo: T, serializer: KSerializer<T>) { .. }
e
I did something like this but the concept is the same. Haven't finished building it out yet, but it's looking like it will work:
Copy code
interface RenderStateSerializer {
  fun <D> serialize(data: D, serializer: KSerializer<D>): ByteArray?
  fun <D> deserialize(data: ByteArray, deserializer: KSerializer<D>): D
}
e
yeah sorry i mean if someone (this guy) has opt-ed in to
InternalSerializationApi
then there’s nothing to prevent this from happening:
Copy code
data class Foo(val bar: String)

fun taco() {
  val foo = Foo("foo")
  persist(foo, Foo:class.serializer())
}
which will happily compile and i believe crash at runtime
j
@eygraber that is basically
BinaryFormat
e
Interesting. With
BinaryFormat
I would need a `serializersModule`which I don't believe I need for my use case