'How to use Generics on this class?
How would one go about implementing generics on MySerializer below?
The SomeGenericClass type is what I would like to make generic.
I understand that this is an object which cannot be generified by definition. How can it be translated into a class to allow generification?
import androidx.datastore.core.Serializer
import kotlinx.serialization.json.Json
object MySerializer: Serializer<SomeGenericClass> {
override val defaultValue: SomeGenericClass
get() = SomeGenericClass()
override suspend fun readFrom(input: InputStream): SomeGenericClass {
return try {
Json.decodeFromString(
deserializer = SomeGenericClass.serializer(),
string = input.readBytes().decodeToString()
)
} catch (e: SerializationException) {
e.printStackTrace()
defaultValue
}
}
override suspend fun writeTo(t: SomeGenericClass, output: OutputStream) {
output.write(
Json.encodeToString(
serializer = SomeGenericClass.serializer(),
value = t
).encodeToByteArray()
)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
