Skip to content

Value classes that implemnet sealed interfaces marked as @Serializable cannot be decoded and will throw runtime error. #3072

@TBSten

Description

@TBSten

Describe the bug

Value classes that implemnet sealed interfaces marked as @serializable cannot be decoded and will crash.
This is because the type of the sealed interface cannot be set during serialization.

To Reproduce

// SealedInterface.kt
@Serializable
sealed interface SealedInterface

@Serializable
@JvmInline
value class ValueClass(val value: String): SealedInterface

// App.kt
val valueClass: ValueClass = ValueClass("value-class-value")
println("valueClass: $valueClass")

val valueClassString = Json.encodeToString(valueClass)
println("  encoded: $valueClassString")

// 💥 will be runtime error !
println("  decoded: ${Json.decodeFromString<SealedInterface>(valueClassString).let { it to it::class }}")

Or sample project

Expected behavior

Since ValueClasses inheriting from SealedInterface are inherently impossible to deserialize, it may be necessary to treat this as a compile-time error.

Environment

  • Kotlin version: 2.2.0
  • Library version: 1.9.0
  • Kotlin platforms: All (In sample project, JVM)
  • Gradle version: 8.14

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions