Data class: modify on copy


#1

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?


#2

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.


#3

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