Skip to content

serializedValue silently loses nullable fields in non-nullable nested objects during read-modify-write #245

Description

@RiteshChandnani

Library version: 1.3.0
Kotlin: 2.1.0
Platform: Android


Description

When using serializedValue with a @serializable class that contains a non-nullable nested object (with a default value) whose fields are all nullable, a read-modify-write cycle silently loses all written values. The write appears to succeed (no exception), but the subsequent read returns the default (null) for every field inside the nested object.


Minimal Reproducible Example

 @Serializable
 data class Document(
     val title: String? = null,
     val metadata: Metadata = Metadata(),
 )
 
 @Serializable
 data class Metadata(
     val author: String? = null,
     val version: Int? = null,
 )
 
 @OptIn(ExperimentalSettingsApi::class, ExperimentalSerializationApi::class)
 class Storage(settings: Settings) {
     var document: Document by settings.serializedValue(
         serializer = Document.serializer(),
         key = "document",
         defaultValue = Document(),
     )
 }
 
 @Test
 fun `nested nullable fields survive read-modify-write`() {
     val settings = Settings()
     val storage = Storage(settings)
 
     // Read-modify-write — update only a field inside the nested object
     storage.document = storage.document.copy(
         metadata = storage.document.metadata.copy(author = "Alice")
     )
 
     // FAILS: returns null instead of "Alice"
     assertEquals("Alice", storage.document.metadata.author)
 }

Expected behaviour
storage.document.metadata.author returns "Alice" after the write.

Actual behaviour
storage.document.metadata.author returns null. The write appears to succeed silently but the value is not recovered on the subsequent read.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions