Skip to content

Inconsistent encoding of empty nullable collections #30

@henrikje

Description

@henrikje

It seems empty values for list and map fields are encoded somewhat inconsistently.

Details

In a top-level class:

  • An empty list for a nullable list field is not encoded. (Would have expected key=[].)
  • An empty map for a nullable map field is encoded as an empty table [key]. (As expected.)

In a nested class:

  • An empty list for a nullable list field is encoded as key=[]. (As expected, but still unexpected because of behavior in a top-level class.)
  • An empty map for a nullable map field is not encoded. (Would have expected [nested.key])

Why?

Because there is a semantical difference between an empty list/table and a null/non-existing one. In my usecase that difference happens to be important.

Also, because 4koma decodes data in the way I expect. An empty array/table becomes an empty list/map, while a non-existing array/table becomes null. I would expect that a toml string can be decoded and re-encoded and the resulting toml should be semantically equal to the original toml.

Example

data class Config(
    val nullableMap: Map<String, Any>?,
    val nullableList: List<String>?,
    val nested: Nested
)
data class Nested(
    val nullableMap: Map<String, Any>?,
    val nullableList: List<String>?,
)

fun main() {
    val mapper = tomlMapper {}
    val toml = mapper.encodeToString(Config(emptyMap(), emptyList(), Nested(emptyMap(), emptyList())))
    println(toml)
}

Expected output:

nullableList = [ ] # this should be present!

[nested]
nullableList = [ ]

[nested.nullableMap] # this should be present!

[nullableMap]

Actual output:

[nested]
nullableList = [  ]

[nullableMap]

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