Data class: modify on copy

I often need to copy a data object to apply some slight modifications. Example:

data class Test(val s: String)
val json: String = "{\"s\": \"  my string  \"}"

var testVal = JSONParser.parse(json)
testVal = testVal.copy(s = testVal.s.trim())

Now, what I would like to write is something like this:

val testVal = JSONParser.parse(json).copy(s = {???}s.trim())

With {…} indicating that I have no idea what to write here. Am I correct that this is not possible right now?

I could do something like

data class Test(val s: String) {
    fun copy(modifier: (Test) -> Test): Test {
        return modifier(this)
    }
}
JSONParser.parse<Test>(json).copy { it.copy(s=it.s.trim()) }

But this is too much boiler plate IMO.

Any suggestions?

You can replace your copy with the standard run:

JSONParser.parse<Test>(json).run{ copy(s=s.trim()) }

Kotlin can distinguish between the parameter s of the copy function and the value s of Test.

1 Like

Thanks. Looks good. I didn’t know about that.