[JAVA-5281] Allow bson-kotlin to support default values where the value is null Created: 03/Jan/24  Updated: 23/Jan/24

Status: Backlog
Project: Java Driver
Component/s: Codecs, Kotlin
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Unknown
Reporter: Ross Lawley Assignee: Ross Lawley
Resolution: Unresolved Votes: 0
Labels: kotlin-quick-wins
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Kotlin supports default values, in data classes where a field is non nullable and has a default value then the default value should be used if the database contains nulls

data class Item(val name:String, val category:String = "default")
 
// This data will error
{ name: "item2", category: null }

A PR has been submitted reporting this issue: https://github.com/mongodb/mongo-java-driver/pull/1260



 Comments   
Comment by Ross Lawley [ 09/Jan/24 ]

I can confirm that there is a configuration in kotlinx with Json that would allow users to work around this:

    @Test
    fun testItem() {
        @Serializable
        data class Item(val name:String, val category:String = "default")
        val json = Json {
            coerceInputValues = true
        }
        val expected = Item("A", "default")
        val string = "{\"name\": \"A\", \"category\": null}"
        val actual = json.decodeFromString<Item>(string)
 
        assertEquals(expected, actual)
 
    }

Generated at Thu Feb 08 09:04:11 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.