Changing value of variable inside argument in kotlin

Viewed 196

In Java you can do the following:

boolean a = true;
if(a = false) {
   //////
}

And a will be set to false and be used after that as argument. But in kotlin, I couldn't find a way to do that, except for:

var a = true
a = false
if(a) {

}

Is there any better way?

1 Answers

You can do this inline in a slightly different order - by writing the value to be assigned (false) first, and using the also scope function to assign it:

var a = true
if(false.also { a = it }) {

}

However, I would not recommend you to do this in either Java or Kotlin, as this is not very readable. There is nothing bad about writing the assignment as a separate statement.

Related