Home > Net >  Kotlin data class - conditional copy?
Kotlin data class - conditional copy?

Time:09-03

I have data class in Kotlin:

data class Foo(a: String, ...)

I would like to make a copy of it with a changed only if some conditions are met.

something like:

foo.copy( a = if(sth){ "baz" } else { this.a } )

but I can't refer to the foo object itself inside the copy function.

CodePudding user response:

data class Foo(var a: String)

You cannot use call have self reference directly inside copy fucntion. You can use scope functions like with to achieve it.

val foo1 = Foo("Hello")
var foo1Copy = with(foo1) {
    copy(a = if (this.a =="Hello") "Hello Again" else "Not Hello" )
}
println(foo1) //Foo(a=Hello)
println(foo1Copy) // Foo(a=Hello Again)


val foo2 = Foo("Hi")
var foo2Copy = with(foo2) {
    copy(a = if (this.a =="Hello") "Hello Again" else "Not Hello" )
}
println(foo2) //Foo(a=Hi)
println(foo2Copy) //Foo(a=Not Hello)

Playground Link

Hope it helps.

  • Related