davidOhara
davidOhara

Reputation: 1008

Kotlin Data class copy extension

I am trying to find a solution for a nice kotlin data class solution. I have already this:

data class Object(
    var classMember: Boolean,
    var otherClassMember: Boolean,
    var example: Int = 0) {

    fun set(block: Object.() -> kotlin.Unit): Object {
        val copiedObject = this.copy()
        copiedObject.apply {
            block()
        }
        return copiedObject
    }

    fun touch(block: Object.() -> kotlin.Unit): Object {
        return this.set {
            classMember = true
            otherClassMember = false
            block() }
    }

}

val test = Object(true,true,1)
val changedTest = test.touch { example = 2 }

the result of this method is that the changedTest object has classMember = true, otherClassMember = false and example = 2

The problem with this solution is, the class properties are not immutable with var declaration. Does somebody have an idea how to optimize my methods to change var to val?

Upvotes: 0

Views: 2781

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170805

If I understood what you want correctly, you can do

data class Object(
    val classMember: Boolean,
    val otherClassMember: Boolean,
    val example: Int = 0) {

    fun touch(example: Int = this.example): Object {
        return copy(
            classMember = true,
            otherClassMember = false,
            example = example)
    }

}

val test = Object(true,true,1)
val changedTest = test.touch(example = 2)

Though you need to repeat parameters other than classMember and otherClassMember but without reflection you can't do better.

Upvotes: 0

nyarian
nyarian

Reputation: 4375

val says that a variable can't change it's value after initialization at the definition point. Kotlin's generated copy method does not modify an existing copy after construction: this method actually uses retrieved values from an object, replaces these values with ones that provided in copy method (if any), and after that just constructs a new object using these values.

So, it is not possible to perform such an optimization if you are going to change object's state after construction.

Upvotes: 1

Related Questions