When I use ReadWriteProperty and -- or ++, it doesn't work as expected

When my code like this, tmp value not changed

      private var tmpValue: Int by MyReadWritePropery()
      fun doWhat(){
           tmpValue = Math.max(tmpValue--, MachineInfo.getInt(MachineInfo.Min_Temperature))
      }
      

When I changed it like this, it works as expected

      private var tmpValue: Int by MyReadWritePropery()

      fun doWhat() {
          tmpValue -= 1
          tmpValue = Math.max(tmpValue, MachineInfo.getInt(MachineInfo.Min_Temperature))
      }

Your code is wrong, maybe your method of MachineInfo.getInt always returns a value less than tmpValue.

Please consider about the code below:

fun main(args: Array<String>) {
    var value: Int = 0
    value = maxOf(value++, -1)  // Use Kotlin's functions instead of Java's
    println(value)
}

What will this code print to your screen?
Sure it’s 0.
Why? It’s because you are comparing 0 and -1 instead of 1 and -1.

When you are using value++ as an actual param to invoke a function, the function always receives value instead of value + 1. after gave value to the function, value + 1 is assigned to the field of value.

So when maxOf is invoked, 0 and -1 are passed to this function to compare. Certainly 0 is returned and assigned to value.

Use prefix decrement: tmpValue = Math.max(--tmpValue, MachineInfo.getInt(MachineInfo.Min_Temperature)). Postfix decrement returns old value.

1 Like

Thanks,I’ve find my fault.Maybe I shouldn’t ask such a simple question here,.