Closed
Description
Consider this code:
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
val module = SerializersModule {
polymorphic(Repository::class) {
subclass(OwnedRepository::class)
}
}
val format = Json { serializersModule = module }
@Serializable(with = PolymorphicSerializer::class)
interface Repository {
val name: String
}
@Serializable
@SerialName("owned")
class OwnedRepository(override val name: String, val owner: String) : Repository
fun main() {
val data: Repository = OwnedRepository("kotlinx.coroutines", "kotlin")
println(format.encodeToString(data))
}
Here an interface is annotated with @Serializable(with = PolymorphicSerializer::class)
and then the variable data
of type Repository
is serialized with format.encodeToString(data)
function. It fails to retrieve the serializer from this annotation:
Exception in thread "main" kotlinx.serialization.SerializationException: Serializer for class 'Repository' is not found. Mark the class as @Serializable or provide the serializer explicitly.
Expected: It should work just as it works when Repository
is used as a property in another serializable class.