Is there a way to accept Serializable types in a f...
# serialization
a
Is there a way to accept Serializable types in a function? Like some supertypes or something? Usecase:
Copy code
fun <T : Any> store(key: String, value: T, serializer: KSerializer<T>) {
    json.stringify(serializer, value)
}

//To, maybe reified
fun <T : SomeSuperTypeForSerializable> store(key: String, value: T) {
    json.stringify(T.serializer(), value)
}
Found out myself, used reflections here, althrough use is discouraged, it looks cleaner, because they are inferred
Copy code
inline fun <reified T: Any> store(key: String, value: T) {
    val serializer = T::class.serializer()
}
n
but that only works on jvm, passing the serializer around would work on other platforms too (most likely)
a
JVM is most stable so, atleast work there😜
Better than nothing :V
b
Would be really nice, but I think it would get quite complicated in Kotlin as it is right now, because the compiler wouldn't just need to know that
T
implements some interface that declares
serializer()
, it would in fact need to assert that
T
has a companion object that implements such an interface. This is one of those areas where C++ templates really shine.
n
well it could also just look for a annotation on the class
@Serializable(with=...)
assuming the compiler can modify the annotation when it injects all the serializable stuff that would at least only be a single marker on the type to match