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

Non-nullable serializer used for nullable field inside generic sealed class, causing null pointer exception.

Open availe opened this issue 3 weeks ago • 0 comments

Describe the bug

When I try serializing a generic sealed class (e.g., Sealed<out T>) where the type argument is nullable (e.g., Sealed<String?>), kotlinx serialization incorrectly attempts to use the non-nullable serializer for the inner type, causing a null pointer exception at runtime.

To Reproduce To reproduce the issue copy the following files:

Main.kt

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
sealed class SerializablePatchable<out T> {
    // What value something is being set to.
    @Serializable
    data class Set<out T>(val value: T) : SerializablePatchable<T>()

    // Not used here for this test, but just for reference.
    // @Serializable data object Unchanged : SerializablePatchable<Nothing>()
}

@Serializable
data class UpdateRequest(
    // Notice how the description field is optional and can be set to null.
    val description: SerializablePatchable<String?>
)

fun main() {
    val data = UpdateRequest(
        // We try to set the value to null.
        description = SerializablePatchable.Set(null)
    )

    val json = Json.encodeToString(data)
    println("Success: $json")
}

build.gradle.kts

plugins {
    kotlin("jvm") version "2.2.21"
    kotlin("plugin.serialization") version "2.2.21"
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")
}

Expected behavior

JSON output: Success: {"description":null}

Actual behavior

java.lang.NullPointerException: Parameter specified as non-null is null: method kotlinx.serialization.internal.StringSerializer.serialize, parameter value

It uses the non-nullable StringSerializer which causes runtime exception.

Environment

  • Kotlin version: 2.2.21
  • Library version: 1.9.0
  • Kotlin platforms: JVM, Native, Wasm
  • Gradle version: Tested using 8.14 and 9.2.1

availe avatar Nov 25 '25 05:11 availe