Skip to content

Inspection: implicitly inferred type for the hierarchy with multiple serializable types should be specified explicitly #1493

@qwwdfsad

Description

@qwwdfsad

Consider the following code (from our own guide):

@Serializable
sealed class Project {
    abstract val name: String
}
            
@Serializable
class OwnedProject(override val name: String, val owner: String) : Project()

fun main() {
    val data = OwnedProject("kotlinx.coroutines", "kotlin")
    println(Json.encodeToString(data))
} 

Json.encodeToString(data) is inferred by the compiler into Json.encodeToString<OwnedProject>(data) and it's not clear whether this is a intended behaviour (OwnedProject is serialized as a regular type) or a bug, and it was implied that OwnedProject should be serialized as a polymorphic type with type discriminator.
To avoid that, Json.encodeToString<Project>(data) should be used instead.

The proposal is to always warn about such call-sites with the quickfix that suggests specifying type explicitly. For polymorphic hierarchies, it would be nice if the quickfix was suggesting to use <BaseType> by default, as it's much easier to find out how to prevent type discriminator from appearing, rather than find out why it's not appearing in the final JSON

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions