Home > OS >  Kotlin inc() operator overloading
Kotlin inc() operator overloading

Time:05-05

I have a little problem to overload inc() operator, precisely to make a postfix and a prefix one.

Here my data class

data class Person(val firstName: String, val name: String, var age: Int) {

    operator fun inc(): Person {
        val tmp = this
        this.age  ;
        return tmp
    }
}

With this, age change before returning so it's only working for prefix version.

How can I do a postfix version of inc() operator ?

CodePudding user response:

There is no way to do what you’re trying to do. You are breaking the contract that the increment operator must not mutate the class. It must return a new instance of the class.

CodePudding user response:

inc is expected to return a new, incremented instance of the class. Since you've got a dataclass, we can use Kotlin's convenience functions that work on dataclasses to get a new instance for you relatively effortlessly.

data class Person(val firstName: String, val name: String, var age: Int) {
  operator fun inc(): Person =
    this.copy(age = this.age   1)
}

Person.copy is one of several dataclass methods generated for you. It takes the same arguments as your primary constructor, with each argument defaulting to the current value on this (i.e. any arguments not passed will be the same as the corresponding values on this). So by passing only the age parameter by name, we modify only the one we want to and leave the others untouched.

  • Related