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

Serialization registration not working with two sealed superclasses

Open waterstopper opened this issue 3 years ago • 1 comments

[UPD]: When serialized classes are in one file, then the bug is not present.

Describe the bug When a serialized class has two sealed superlcasses, it appears not registered.

To Reproduce https://www.youtube.com/watch?v=hlYqZxdM270 - here is a video showing how to create a bug (there is a comment explaining in detail what is happening) And here is the code: Rand.kt

@Serializable
@SerialName("Rand")
sealed class Rand {
   abstract fun determine():Any
}

RandNum.kt

@Serializable
@SerialName("RandNum")
sealed class RandNum:Rand() {
    @Contextual abstract val from: Number
    @Contextual abstract val until: Number
    @Contextual abstract val step: Number

    abstract override fun determine():Number
}

RandInt.kt

@Serializable
@SerialName("RandInt")
class RandInt(
    override val from: Int = 0,
    override val until: Int = 1,
    override val step: Int = 1
) : RandNum() {

    override fun determine(): Int =
        (Random.nextInt(from, until).toDouble() / step).roundToInt() * step
}

Main.kt

fun main(args: Array<String>) {
    val rnd:Rand = RandInt(5,7,2)
    val str = Json.encodeToString(rnd)
    println(str)
    val obj = Json.decodeFromString<Rand>(str)
    println(obj)
}

Expected behavior "Registration chain" of any length should work from the first run without rerunning code and tweaking inheritances.

Environment

  • Kotlin version: [1.5.31]
  • Library version: [1.3.2]
  • Kotlin platforms: [JVM Adopt OpenJDK 11.0.9.1]
  • Gradle version: [7.1 (not sure, found a folder with this name in .gradle folder. Couldn't understand where to find Gradle version)]
  • IDE version [IntellijIDEA Ultimate Edition 2021.2.2]

waterstopper avatar Jan 26 '22 11:01 waterstopper

Fix via codegen https://github.com/MEJIOMAH17/kotlinx-serialization-sealed-class-support

MEJIOMAH17 avatar Oct 14 '24 13:10 MEJIOMAH17

Duplicate of #1541 — problems with incremental compilation

sandwwraith avatar Dec 13 '24 18:12 sandwwraith