kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

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

Open TBSten opened this issue 3 months ago • 0 comments

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

TBSten avatar Aug 30 '25 03:08 TBSten