kotlinx.serialization
kotlinx.serialization copied to clipboard
Value classes that implemnet sealed interfaces marked as @Serializable cannot be decoded and will throw runtime error.
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 }}")
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